Obtain Local Host IP in C# 5

This program illustrates how we can obtain the IP address of Local Host. If a string parameter is supllied in the exe then the same is used as the local host name. If not then the local host name is retrieved and used. See the code below:


using System;
using System.Net;

namespace Obtain_IP_Address_in_C_Sharp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("*************************************");
            Console.WriteLine("*****www.code-kings.blogspot.com*****");
            Console.WriteLine("*************************************\n");

            String StringHost;

            if (args.Length == 0)
            {
                // Getting Ip address of local machine...
                // First get the host name of local machine.
                StringHost = System.Net.Dns.GetHostName();
                Console.WriteLine("Local Machine Host Name is: " + StringHost);
                Console.WriteLine("");
            }
            else
            {
                StringHost = args[0];
            }

            // Then using host name, get the IP address list..
            IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(StringHost);
           
            IPAddress[] address = ipEntry.AddressList;

            for (int i = 0; i < address.Length; i++)
            {
                Console.WriteLine("");
                Console.WriteLine("IP Address Type {0}: {1} ", i, address[i].ToString());
            }
            Console.Read();
        }
    }
}
Custom Search