简体   繁体   English

获取IP地址

[英]Getting the ip-address

In C#: 在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. 在此代码中, IPHostEntry变量包含计算机的所有IP地址。 Now, as far as I know, Windows vista returns a number of IP addresses some in hexadecimal, some in decimal notation and so on. 现在,据我所知,Windows vista返回一些十六进制的IP地址,一些是十进制表示法,依此类推。

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: 问题是所需的十进制表示法改变了它在IPHostEntry变量中的位置:它最初出现在最后一个位置,因此可以使用以下代码访问:

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: 但是,在更改计算机的IP地址后,它现在显示在第二个最后位置,因此需要使用以下代码进行访问:

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?? 是否有任何代码以十进制表示法检索IP地址,而不IPHostEntryIPHostEntry变量中的位置?

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. 假设你只想要IPv4地址,我现在正在使用这个代码(修改了一些用于发布),这个代码足够强大,可供我使用。 Just invoke ToString on the result to get the address: 只需在结果上调用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
}

The 169.254.* part might seem like a hack, but is documented in IETF RFC 3927 . 169.254。*部分可能看起来像是一个黑客,但在IETF RFC 3927中有记录

I believe what you are asking is can you differentiate between the IPv4 and IPv6 address returned from your DNS query. 我相信您要问的是,您可以区分DNS查询返回的IPv4和IPv6地址。 The answer is yes. 答案是肯定的。 Check the AddressFamily property on the IPAddress and make sure it returns InterNetwork . 检查IPAddress上的AddressFamily属性 ,并确保它返回InterNetwork

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM