Title: Programmatically Retrieve Your IP Address Behind a Router / Proxy / Gateway Using Delphi Code
Code posted by David Reed on the Delphi Programming Forum
An IP Address (Internet Protocol Address) identifies and allows computers (printers, routers) to communicate with each other on a computer network.
The Internet is built on TCP/IP connections. The TCP part describes how two computers set up a connection to each other and transfer data. IP part primarily deals with how to get a message routed across the Internet.
If your machine is a part of a home (office) network you most probably have some kind of a router which joins the home's local area network (LAN) to the wide-area network (WAN) of the Internet.
Typically, the internal, LAN (Local Area Network) IP address is normally set to an IP number similar to "192.68.0.11".
The external, WAN (Wide Area Network) IP address of the router is set when the router connects to the Internet service provider.
If you need to know the WAN-IP of your router using Delphi code, you can take advantage of the "http://www.whatismyip.com" service which can reveal the IP address of machine:
WAN IP Address
The code below can be used to get the IP address of a router your machine is using to connect to the Internet.
uses ScktComp;
function GetHTML(const AURL: string): string;
var
sHead,sHost,sPage: string;
x,xCnt,xCntTotal: integer;
sock: TClientSocket;
ws: TWinSocketStream;
ss: TStringStream;
buff: array[0..4095] of char;
const
CrLf = #13#10;
begin
Result := '';
sHost := AURL;
x := Pos('//',sHost) ;
if x 0 then
System.Delete(sHost,1,x+1) ;
x := Pos('/',sHost) ;
if x 0 then
begin
sPage := Copy(sHost,x,Length(sHost)) ;
System.Delete(sHost,x,Length(sHost)) ;
end
else
begin
sPage := '/';
end;
sock := TClientSocket.Create(nil) ;
try
try
sock.ClientType := ctBlocking;
sock.Port := 80;
sock.Host := sHost;
sock.Open;
// set timeout to 20 seconds
ws := TWinSocketStream.Create(sock.Socket,20000) ;
ss := TStringStream.Create('') ;
try
sHead := 'GET ' + sPage + ' HTTP/1.0 ' + CrLf + 'Host: ' + sHost + CrLf + CrLf;
StrPCopy(buff,sHead) ;
ws.Write(buff,Length(sHead) + 1) ;
ws.Position := 0;
FillChar(buff,SizeOf(buff),0) ;
repeat
xCnt := ws.Read(buff,SizeOf(buff)) ;
xCntTotal := xCntTotal + xCnt;
ss.Write(buff[0],xCnt) ;
until xCnt = 0;
Result := ss.DataString;
finally
ws.Free;
ss.Free;
end;
except
end;
finally
sock.Free;
end;
end;
Here's how to use the above function to get your WAN IP from the www.whatismyip.com:
var
ip: string;
begin
with TStringlist.Create do
try
Text := GetHTML('www.whatismyip.com/automation/n09230945.asp') ;
if Count 0 then ip := Strings[Count - 1];
finally
Free;
end;
ShowMessage('Your (gateway / router / proxy) IP address is ' + ip) ;
end;
Note: if you need to programmatically determine the LAN IP address of a machine running your Delphi application, the My LAN IP with Delphi provides the code you can use.