Friday 11 July 2014

Finding your IP address

Different operating systems have different methods of finding the IP address. Unfortunately, none of them are platform neutral (in other words, what someone under Linux would do is not what someone using a Windows box would do). If I didn't care about the underlying operating system I could simply read in the results of either /sbin/ifconfig or ipconfig /all (both return all of the network addresses on a machine, all that has to be done is search the text for something that isn't either 127.0.0.1 or 0.0.0.0.) - fine if I know what the target machine is.

But what if I don't? How can I find my IP address in a way that will work on all machines, irrespective of if the framework is Mono based or Microsoft based?

Thankfully, it's as easy as this...

using System;
using System.Net;

namespace dns
{
    public class dns
    {
        public static int Main (string [] args)
        {
       
          String strHostName = "";
          if (args.Length == 0)
          {
              // Getting IP address of local machine...
              // First get the host name of local machine.
              strHostName = Dns.GetHostName ();
              Console.WriteLine ("Local Machine's Host Name: " + 
                                 strHostName);
          }
          else
          {
              strHostName = args[0];
          }
         
          // Then using host name, get the IP address list..
          // IPHostEntry ipEntry = Dns.GetHostByName (strHostName);
          IPHostEntry ipEntry = Dns.GetHostEntry(strHostName);
          IPAddress [] addr = ipEntry.AddressList;
         
          int ips = 0;
          foreach (IPAddress ipaddr in ipEntry.AddressList)
          {
              Console.WriteLine("IP #" + ++ips + ": " +
                                ipaddr.ToString());
          }
          Console.ReadKey();
          return 0;
        }   
    }
}

No comments:

Post a Comment