find Internet IP through router with Delphi

Posted by webmaster Guido on January 14, 2005

In Reply to: Internet IP through router posted by Giovanni Caramia p12316 on January 03, 2005

: Is there a component or some code that can tell me my ip when i'm connected to internet through a router?

Your IP address as it is seen *externally* can be different from your *local* IP. This is the case if you access the Internet through another device on your network (router, firewall, another network computer,...)

You have to ask another computer on the Internet how it sees your IP. There are pages on the Internet, that display your IP. Surf to such a page and read its text.
A working example: htp://checkip.dyndns.org/
(because we can't be sure that this page will exist forever, it's preferable that you put a similar page online on your own site, that shows the visitor's IP).

Writing a Delphi program for this purpose:

1. You need a component that can access a webpage, i.e. that can do a HTTP-get (examples: NMHTTP or similar HTTP component).
Note: the "personal" Delphi versions don't have Internet components, but there are freeware as well as shareware components available.
2. Do an HTTP-get of the webpage that displays your IP, for example htp://checkip.dyndns.org/
3. From the body of the page source, extract your IP.
Let's suppose that the text of the page is "Current IP Address: 123.456.789.10"
You first have to find the starting position of "Current IP Address: " and then extract the IP that follows this text. In the page returned by htp://checkip.dyndns.org/ that is everything until the tag </body>.

Let's assume you have received the body of the page in a string variable HTMLBody.

const
  StartText = 'Current IP Address: ';
  EndText = '</body>';
var
  StartPos, Leng: integer;
  IP: string;
begin
  StartPos := Pos(StartText, HTMLBody) + Length(StartText);
  Leng := Pos(EndText, HTMLBody) - StartPos;
  IP := Copy(HTMLBody, StartPos, Leng);

Cheers,
webmaster Guido


Delphi Tutorials -- by DelphiLand