获取IP地址 [英] Getting the ip-address
问题描述
在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");
}
在此代码中, IPHostEntry
变量包含计算机的所有IP地址。
现在,据我所知,Windows Vista返回的IP地址数量以十六进制表示,以十进制表示,等等。
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.
问题是所需的十进制表示法会更改其在 IPHostEntry
变量中的位置:最初是在最后一个位置,因此可以使用以下代码访问:
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();
但是,更改计算机的IP地址后,它现在出现在倒数第二个位置,因此需要可以使用以下代码进行访问:
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();
是否有任何代码以十进制表示法检索IP地址,而不管其在<$ c中的位置如何$ c> IPHostEntry 变量?
Is there any code that retrieves the IP addresses in decimal notation irrespective of its location in the IPHostEntry
variable??
推荐答案
假设您只需要IPv4地址,当前正在使用此代码(为发布做了一些修改),足以供我使用。只需在结果上调用ToString即可获取地址:
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
}
169.254。*部分似乎像黑客一样,但记录在 IETF RFC 3927 。
The 169.254.* part might seem like a hack, but is documented in IETF RFC 3927.
这篇关于获取IP地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!