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.
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.
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 JSON
interpreter 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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With