开发者

How to get external (public) IP in Delphi

I need to get my external (public) IP address from Delphi.

The same IP 开发者_运维知识库that is shown by www.whatismyip.com for example.

How can I do that ? Winsock doesn't allow this.


You can use this website: http://ipinfo.io/json. It returns the information about your current internet connection in JSON format.

In delphi you need use IdHTTP this way: IdHTTP1.Get('http://ipinfo.io/json') and it will returns a string with all the data. You can use a JSONinterpreter you like or you can use the lkJSON as the following example:

json := TlkJSON.ParseText(MainEstrutura.IdHTTP1.Get('http://ipinfo.io/json')) as TlkJSONobject;

str := json.Field['ip'].Value;

I hope help you.


I don't think you can. Well, you could call some service that tells you what your IP address appears to be, ( ex: http://www.whatismyip.com/ ) and figure it out from the response. But I don't think anything on your PC will be able to tell you what your IP address looks like, to the outside world.

Untested, but I think you can do this with Indy:

MyPublicIP := IdHTTP1.Get('http://automation.whatismyip.com/n09230945.asp');

Please review the rules/policy at: http://www.whatismyip.com/faq/automation.asp before using this.


this works for me:

  uses JSON,IdHTTP;
  function GetIP():String;
  var  LJsonObj   : TJSONObject;
  str:string;
  http : TIdHttp;
  begin
    str:='';
    http:=TIdHTTP.Create(nil);
    try
        str:=http.Get('http://ipinfo.io/json');
        LJsonObj:= TJSONObject.ParseJSONValue(TEncoding.ASCII.GetBytes(str),0)           as TJSONObject;
        str := LJsonObj.Get('ip').JsonValue.Value;
        LJsonObj.Free;
        http.Free;
    Except
    end;
    result:=str;
end;


From memory, untested:

function GetMyHostAddress: string;
var
   http: IWinHttpRequest;
begin
   http := CreateOleObject('WinHttp.WinHttpRequest5.1') as IWinHttpRequest;
   http.Open('GET', 'http://automation.whatismyip.com/n09230945.asp', False);
   http.Send(EmptyParam);

   if http.StatusCode = 200 then
      Result := http.ResponseText
   else
      Result := '';
end;


Function GetMyIP:string;
var
  xmlhttp:olevariant;
  s,p:integer;
  temp:string;
begin
  result:=emptystr;
  xmlhttp:=CreateOleObject('Microsoft.XMLHTTP');
  try
    xmlhttp.open('GET', 'http://www.findipinfo.com/', false);
    xmlhttp.SetRequestHeader('User-Agent','Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3');
    xmlhttp.send(null);
  except
    exit;
  end;
  if(xmlhttp.status = 200) then
  temp:=trim(VarToStr(xmlhttp.responseText));
  xmlhttp:=Unassigned;
  s:=pos('Address Is:',temp);
  if s>0 then
  inc(s,11)
  else
  exit;
  temp:=copy(temp,s,30);
  s:=pos('<',temp);
  if s=0 then exit
  else
  dec(s);
  result:=trim(copy(temp,1,s));
end;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜