Wednesday 29 August 2007

Delphi code to fetch your own public IP address

function whatismyip(): String;
var anurl: String;
var r:TregExpr;
var myip: string;
begin
anurl := IdHTTP1.Get('http:\\www.whatismyip.com');
r:= TregExpr.Create;
r.Expression := '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}';
if r.Exec(anurl) then myip := r.Match[0];
r.Destroy;
whatismyip:=myip;
end;

This snippet requires indy and also regular expressions from http://regexpstudio.com/

There is a version using windows sockets here :-
http://www.delphifusion.com/forum/showthread.php?t=247

Power basic to fetch your own external IP address.

This Power Basic 8.0 snippet fetches your external IP address OR beeps.

' find our ip address by fetching a page from whatismyip.com
hTCP&=FREEFILE
TCP OPEN "www" AT "www.whatismyip.com" AS hTCP&
IF ERR THEN
BEEP
ELSE
TCP PRINT hTCP&,_
"GET / HTTP/1.1" +CHR$(13)+CHR$(10)+_
"Host: www.whatismyip.com" +CHR$(13)+CHR$(10)+_
"Accept: text/html, */*" +CHR$(13)+CHR$(10)+_
"Accept-Encoding: identity"+CHR$(13)+CHR$(10)+_
"User-Agent: Mozilla/3.0" +CHR$(13)+CHR$(10)
TCP RECV hTCP&, 2048, buffer$
TCP CLOSE hTCP&

REGEXPR "[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+" IN buffer$ TO iPOS&, iLEN&

IF iPOS&>0 THEN ' save the present ip..
myip$ = MID$(buffer$,iPOS&, iLEN&)
CONTROL SET TEXT CBHNDL, %IDC_TEXTBOX1, myip$
outfile&=FREEFILE
OPEN "oldip.txt" FOR OUTPUT AS #outfile&
WRITE #outfile&, myip$
CLOSE #outfile&
END IF
END IF