Tuesday, June 22, 2010

Determine Online (WAN) IP - Address

In the previous post I showed, how to determine the IP - address of the computer in the local network (in the LAN - Local Area Network).
In this post now I want to explain, how to get the online IP address of the computer. In the internet every connection node has its own IP - address, by which it is identified.
For the communication this one is important and not the local IP - address. This online IP is also called WAN (Wide Area Network) IP - address.
The connection nodes can be anything, computers, mobile phones or routers. Probably at home for you it is a router, since you probably are connected by a router to the internet, to which again multiple computers are connected.
Note that there is only one online IP per router, the computers behind it thus have all the same online IP and are identified by the router through their local IPs.

Also after an extended search I did unfortunately not find a .Net function determining this online IP -
so we have to use some tricks to get it.
There are websites, as for example http://www.wieistmeineip.de/, which can show the online IP.
We now simply read-out such a website with our C# application.
The following example uses a Webclient control, which downloads the sourcecode of the page.
In the source code of the page mentioned above the IP - address is saved in the following context:
<h1 class="ip">xx.xxx.xxx.xxx</h1>.
So the program scans the source code for appearances of the string <h1 class="ip"> and from there one for appearances of </h1>.
The string between this positions then is the WAN IP-address:
System.Net.WebClient IPGetter = new System.Net.WebClient();
// download source code of the page and save in variable SourceCode
string SourceCode = IPGetter.DownloadString(@"http://www.wieistmeineip.de/");

// look for the right starting position
int IPStartPosition = SourceCode.IndexOf("class=\"ip\">");
// look for the right ending position
int IPEndPosition = SourceCode.IndexOf(@"</h1>", IPStartPosition);
// read-out the ip - address between the markers
string IP = SourceCode.Substring(IPStartPosition + ("class=\"ip\">").Length, IPEndPosition - (IPStartPosition + ("class=\"ip\">").Length));

No comments:

Post a Comment