Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the ip-address

In C#:

IPHostEntry IPHost = Dns.GetHostEntry(Dns.GetHostName());

for (int i = 0; i < IPHost.AddressList.Length; i++)
{
    textBox1.AppendText("My IP address is: " 
        + IPHost.AddressList[i].ToString() + "\r\n");
}

In this code, the IPHostEntry variable contains all the IP addresses of the computer. Now, as far as I know, Windows vista returns a number of IP addresses some in hexadecimal, some in decimal notation and so on.

The problem is that the decimal notation which is desired changes its location in the IPHostEntry variable: It initially was occuring in the last location and so could be accessed with the code:

string ipText = IPHost.AddressList[IPHost.AddressList.Length - 1].ToString();

However after changing the IP address of the computer, it now appears in the 2nd last location and so needs to be accessed using the code:

string ipText = IPHost.AddressList[IPHost.AddressList.Length - 2].ToString();

Is there any code that retrieves the IP addresses in decimal notation irrespective of its location in the IPHostEntry variable??

like image 662
saurabh Avatar asked Dec 18 '22 07:12

saurabh


2 Answers

Assuming you only want the IPv4 address, I'm currently using this code (modified a bit for posting) which is robust enough for my use. Just invoke ToString on the result to get the address:

// return the first IPv4, non-dynamic/link-local, non-loopback address
public static IPAddress GetIPAddress()
{
    IPAddress[] hostAddresses = Dns.GetHostAddresses("");

    foreach (IPAddress hostAddress in hostAddresses)
    {
        if (hostAddress.AddressFamily == AddressFamily.InterNetwork &&
            !IPAddress.IsLoopback(hostAddress) &&  // ignore loopback addresses
            !hostAddress.ToString().StartsWith("169.254."))  // ignore link-local addresses
            return hostAddress;
    }
    return null; // or IPAddress.None if you prefer
}

The 169.254.* part might seem like a hack, but is documented in IETF RFC 3927.

like image 175
EventHorizon Avatar answered Dec 30 '22 22:12

EventHorizon


I believe what you are asking is can you differentiate between the IPv4 and IPv6 address returned from your DNS query. The answer is yes. Check the AddressFamily property on the IPAddress and make sure it returns InterNetwork.

like image 26
JP Alioto Avatar answered Dec 30 '22 20:12

JP Alioto