4

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??

4

3 回答 3

10

假设您只想要 IPv4 地址,我目前正在使用此代码(针对发布进行了一些修改),它对于我的使用来说足够强大。只需在结果上调用 ToString 即可获取地址:

// 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
}

169.254.* 部分可能看起来像 hack,但在IETF RFC 3927中有记录。

于 2009-06-22T21:10:23.147 回答
1

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.

于 2009-06-22T20:36:00.237 回答
1

您的十六进制地址是 IPv6,4 个十进制数字是 ipv4。

于 2009-06-22T21:03:48.607 回答