Search code examples
c#ip-address

Formatting IP address in C#


I used this hostInfo.AddressList to get the machine IP address. It returns it in the letter format, such as ff80::c9c9:b2af:aa0f:e2d2%12, what I want is to format it to a IP address format (digits).

I am using C#, .net 3.5.


Solution

  • The format you gave is the correct way to represent an IPv6 address. There does not exist an A.B.C.D format to represent IPv6 addresses.

    What's happening is you are getting a list of addresses both IPv4 and IPv6. You're looking for the IPv4 ones.

    string GetFirstIPv4Address()
    {
        IPAddress[] addressList = Dns.GetHostAddresses(hostname);
    
        foreach (IPAddress ip in addressList)
        {
            if (ip.AddressFamily.ToString() == "InterNetwork")
            {
                //This is an IPv4 address
                return ip.ToString();
            }
        }
        return "127.0.0.1";
    }