Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 321
chubbyk Avatar asked Aug 10 '11 17:08

chubbyk


People also ask

How do I find my IP address in Delphi?

To obtain the computer's IP address, we must use GetHostByName in conjunction with GetHostName. Each computer is called a host and we can get the hostname with a special function call: GetHostName. We then use GetHostByName to get the IP-address, related to this hostname.


2 Answers

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.

like image 144
pedro.olimpio Avatar answered Oct 04 '22 18:10

pedro.olimpio


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;
like image 25
Salim Lachdhaf Avatar answered Oct 04 '22 20:10

Salim Lachdhaf