Click here to Skip to main content
12,816,775 members (33,985 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

21K views
15 bookmarked
Posted 16 Jan 2012

Finding the External IP Address of Your Machine, With a Timeout, in C#

, 16 Jan 2012 CPOL
Rate this:
Please Sign up or sign in to vote.
How to find the external IP address of your machine, with a timeout, in C#.

If you try to find the IP address your machine is using, you can follow two paths. The most obvious one is:

string host = System.Net.Dns.GetHostName();
System.Net.IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(host);
System.Net.IPAddress[] addr = ipEntry.AddressList;
for (int i = 0; i < addr.Length; i++)
{
    if (addr[i].AddressFamily != System.Net.Sockets.AddressFamily.InterNetwork)
        continue;
    return addr[i].ToString();
}

return "";

Unfortunately, in most cases, people are connected to the internet through a router, and therefore each machine is assigned with an internal IP address of the private LAN network, assigning the external IP address to the router only, not to each machine. Finding this external address directly is not trivial, as you would need to deal with the router itself, with different router models, etc.

The easiest way to find the external IP address is to do a web request to one of the several websites out there specially designed to provide you with that address, like whatismyipaddress.com, www.whatismyip.com, etc. In this case, we will use the last one.

Of course, doing a web request can take time, especially if there is no internet connection available, as the default timeout can take several seconds. This function will do the job for you, and accept a custom timeout:

/// <summary>
/// This function uses a Web request to find the external IP Address your machine is using
/// </summary>
/// <param name="pTimeOutMiliSeconds">Number of miliseconds to wait for a response
/// </param>
/// <returns></returns>
public static string GetExternalIP(int pTimeOutMiliSeconds)
{
   string whatIsMyIp = "http://automation.whatismyip.com/n09230945.asp";
   WebClient wc = new WebClient();
   UTF8Encoding utf8 = new UTF8Encoding();
   try
   {
      string ipaddr = null;
      bool done = false;

      wc.DownloadDataCompleted += new 
      DownloadDataCompletedEventHandler((object sender, 
                 DownloadDataCompletedEventArgs e) =>
      {
         ipaddr = utf8.GetString(e.Result);
         done = true;
      });

      wc.DownloadDataAsync(new Uri(whatIsMyIp));
      System.DateTime startTime = System.DateTime.Now;
      while (!done)
      {
         System.TimeSpan sp = System.DateTime.Now - startTime;

         // We should get a response in less than timeout.
         // If not, we cancel all and return the internal IP Address
         if (sp.TotalMilliseconds > pTimeOutMiliSeconds)
         {
            done = true;
            wc.CancelAsync();
         }
      }
      return ipaddr;
   }
   catch
   {
      return null;
   }
   finally
   {
      if (wc != null)
      {
         wc.Dispose();
         wc = null;
      }                
   }
}

It works pretty obviously. It just uses the DownloadDataAsync method, instead of the synchronous DownloadData, and waits for a certain amount of time. If no response is received in that time, it cancels the async method and returns null.

Hope it helps!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Inaki Ayucar
Software Developer (Senior)
Spain Spain
Inaki Ayucar is a Microsoft MVP in DirectX/XNA, and a software engineer involved in development since his first Spectrum 48k, in the year 1987. He is the founder and chief developer of The Simax Project (www.simaxvirt.com) and is very interested in DirectX/XNA, physics, game development, simulation, C++ and C#.

His blog is: http://graphicdna.blogspot.com

To contact Inaki: iayucar@simax.es

You may also be interested in...

Pro
Pro

Comments and Discussions

 
SuggestionBloated Pin
jaredbroad10-Nov-12 22:47
memberjaredbroad10-Nov-12 22:47 
GeneralRe: Bloated Pin
edureis4-Jul-13 10:45
memberedureis4-Jul-13 10:45 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.170308.1 | Last Updated 16 Jan 2012
Article Copyright 2012 by Inaki Ayucar
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid