用户名:  密码:   
您当前的位置:首页 > 程序设计 >  Delphi > 

获取公网IP

上次修改时间: 2021-05-31 10:59:07      来源:网络总结      作者:钢铁长陈
上一页      路径:DSD\Learn\Delphi语言\      下一页

获取公网IP

可以使用的网站:
https://www.123cha.com/ip/

使用idhttp控件出现的问题:
提示: http/1.1 302 Moved Temporarily.
原因:你所连接的页面进行了Redirect.
解决方法:将IdHTTP.HandleRedirects:=True;

提示: Connection Closed Gracefully.
原因: 百度屏蔽了indy的客户端标识的 Mozilla/3.0 (compatible; Indy Library),把‘Indy Library’去掉就可以了 
解决方法:
把iphttp控件的Request.UserAgent改一下, 如:IdHTTP.Request.UserAgent := 'tieguo test';

 

方法二: 成功
function GetWebPage(URL: string):string;
var
IDHTTP: TIDHttp;
ss: String;
begin
  IDHTTP:= TIDHTTP.Create(nil);
  try
    try
    idhttp.Disconnect;
    idhttp.HandleRedirects:= true; //必须支持重定向否则可能出错
    idhttp.ReadTimeout:= 30000; //超过这个时间则不再访问
    //idhttp.Request.UserAgent:=  Mozilla/3.0 (compatible; Indy Library); Mozilla/3.0 (compatible; Indy Library)
    IdHTTP.Request.UserAgent := 'tieguo test';
    ss:=idhttp.Get(url);
    //ss:=UTF8ToAnsi( ss); //UTF8编码转换
    if IDHTTP.ResponseCode=200 then
    Result := ss;
    except
    //ss:='';
    end;
  finally
  IDHTTP.Free;
  end;
end;


方法一: 失败
uese idhttp1;
function GetPublicIP: string;
var
   strIP, URL: string;
   iStart, iEnd: Integer;
   MyIdHTTP: TIdHTTP;
begin
  Result := '';
  MyIdHTTP := TIdHTTP.Create(nil);
  try
       try
         URL := MyIdHTTP.Get('http://www.ip138.com/');  //该句不能执行
       except
       end;
  finally
       MyIdHTTP.Free;
  end;

  if Length(URL) <> 0 then
   begin
     iStart := Pos('[', URL);
     iEnd := Pos(']', URL);
     if (iStart <> 0) and (iEnd <> 0) then
     begin
       strIP := Trim(Copy(URL, iStart + 1, iEnd - iStart - 1));
       if strIP <> '' then
         Result := strIP;
     end;
   end;
end;

方法三:未测试
function pro_result(str:string):string ;//封装了成一个匹配的处理函数
var
  i_0,i_1:Integer;
  flag:Boolean;
  str_1,temp_result:string;
begin
  temp_result:='';
  while Pos('查询结果',str)<>0 do
  begin
    i_1:=Pos('</span>',str);
    i_0:=Pos('查询结果',str);
    temp_result:=temp_result+Copy(str,i_0,i_1-i_0)+#13#10;
    Delete(str,1,Pos('</span>',str));
  end;
  temp_result:=StringReplace(temp_result,' ','',[rfreplaceall,rfignorecase]);
  Result:=temp_result;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  temp,str_1,str_2:string;
  i:Integer;
begin
  Memo1.Text:=IdHTTP1.Get('http://www.ipseeker.cn');
  temp:=Memo1.Text;
  i:=Pos('查询结果',temp);
  str_1:=Copy(temp,i,254);
  str_2:=pro_result(str_1);
  Memo2.Text:=str_2;
end;

方法四
获取公网ip
uses msxml, RegularExpressions;

function GetPublicIP:string;
var
  req: IXMLHTTPRequest;
begin
  req := CoXMLHTTP.Create;
  req.open('get', 'http://city.ip138.com/ip2city.asp', False, EmptyStr, EmptyStr);
  req.send('');
  Result := TRegEx.Match(req.responseText, '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}').Value; 
end;