我知道这可能是白费力气,但也许这能帮到别人。我到处寻找一种方法来找到我的本地IP地址,但我发现到处都说要使用:
Dns.GetHostEntry(Dns.GetHostName());
I don't like this at all because it just gets all the addresses assigned to your computer. If you have multiple network interfaces (which pretty much all computers do now-a-days) you have no idea which address goes with which network interface. After doing a bunch of research I created a function to use the NetworkInterface class and yank the information out of it. This way I can tell what type of interface it is (Ethernet, wireless, loopback, tunnel, etc.), whether it is active or not, and SOOO much more.
public string GetLocalIPv4(NetworkInterfaceType _type)
{
string output = "";
foreach (NetworkInterface item in NetworkInterface.GetAllNetworkInterfaces())
{
if (item.NetworkInterfaceType == _type && item.OperationalStatus == OperationalStatus.Up)
{
foreach (UnicastIPAddressInformation ip in item.GetIPProperties().UnicastAddresses)
{
if (ip.Address.AddressFamily == AddressFamily.InterNetwork)
{
output = ip.Address.ToString();
}
}
}
}
return output;
}
现在要获取以太网接口的IPv4地址:
GetLocalIPv4(NetworkInterfaceType.Ethernet);
或者你的无线接口:
GetLocalIPv4(NetworkInterfaceType.Wireless80211);
如果您试图获取无线接口的IPv4地址,但您的计算机没有安装无线卡,它将只返回一个空字符串。以太网接口也是如此。
编辑:
It was pointed out (thanks @NasBanov) that even though this function goes about extracting the IP address in a much better way than using Dns.GetHostEntry(Dns.GetHostName()) it doesn't do very well at supporting multiple interfaces of the same type or multiple IP addresses on a single interface. It will only return a single IP address when there may be multiple addresses assigned. To return ALL of these assigned addresses you could simply manipulate the original function to always return an array instead of a single string. For example:
public static string[] GetAllLocalIPv4(NetworkInterfaceType _type)
{
List<string> ipAddrList = new List<string>();
foreach (NetworkInterface item in NetworkInterface.GetAllNetworkInterfaces())
{
if (item.NetworkInterfaceType == _type && item.OperationalStatus == OperationalStatus.Up)
{
foreach (UnicastIPAddressInformation ip in item.GetIPProperties().UnicastAddresses)
{
if (ip.Address.AddressFamily == AddressFamily.InterNetwork)
{
ipAddrList.Add(ip.Address.ToString());
}
}
}
}
return ipAddrList.ToArray();
}
现在,这个函数将返回指定接口类型的所有分配地址。现在要获得单个字符串,可以使用. firstordefault()扩展名返回数组中的第一项,如果数组为空,则返回空字符串。
GetLocalIPv4(NetworkInterfaceType.Ethernet).FirstOrDefault();