Monday, 25 November 2013

Get IP address and Host Name of Local Computer

In the Blog of MSDN i found and article to get host and IP address of computer I wrote a code to get it and it gives both address of IPV6 and IPV4 and we know that there is an array of type IPAddress  . and with the help of foreach it will give all address of computer and if you have virtual machine installed then it will also give IP address of this also.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;

namespace Networking
{
    class Program
    {
        static void Main(string[] args)
        {

            Program.gethostname();
        }
        public static void gethostname()
        {
            string hostname = Dns.GetHostName();
           
            IPAddress [] ipaddress = Dns.GetHostAddresses(hostname);
            foreach (IPAddress x in ipaddress)
            {
                Console.Write("this is computer name:" + hostname + "and IP address is: " + x);
                Console.ReadLine();
            }
            Console.ReadLine();
        }
    }
}

IF you pass null string in  GetHostAddresses() method it will return same result as it is when pass hostname string in it. look at the following code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;

namespace Networking
{
    class Program
    {
        static void Main(string[] args)
        {

            Program.gethostname();
        }
        public static void gethostname()
        {
            string hostname = Dns.GetHostName();
            string k = "";
            IPAddress [] ipaddress = Dns.GetHostAddresses(k);
            foreach (IPAddress x in ipaddress)
            {
                Console.Write("this is computer name:" + hostname + "and Ipa address is: " + x);
                Console.ReadLine();
            }
            Console.ReadLine();
        }
    }
}