Download : MyIP.zip Recently a friend of mine asked me how he could determine his external IP address. I told him that there are various websites (including my own) he could go to. Particularly, he could go to WhatIsMyIP and easily figure out his external IP address. Or he could simply go to his router web interface to figure it out.
Simple as it is, there are times that you don’t have access to a webbrowser (e.g. when you are on a server). Also, having to go through a website or a couple of clicks to figure that out does not seem to be very convenient. So I decided to write a simple program to do that. As it turned out, it is quite simple to achieve this.
The program I wrote basically goes to WhatIsMyIP and grabs the corresponding IP address and displays it on the screen. The code to do this is shown below (C#):
HttpWebRequest r =(HttpWebRequest)WebRequest.Create("http://www.whatismyip.com/");
WebResponse wResponse = r.GetResponse();
Stream rStream = wResponse.GetResponseStream();
StreamReader reader = new StreamReader(rStream, Encoding.ASCII);
string respHTML = reader.ReadToEnd();
Regex reg = new Regex(@"(\d{1,3}\.){3}\d{1,3}", RegexOptions.Multiline);
Match m = reg.Match(respHTML);
Console.WriteLine(m.Value);
It first create a web request and then retrieves the response (raw html). The regular expression basically parses for any valid ip addresses. The program finally writes out the matching IP.