找出活动的本地IP [英] Find out the active local IP
本文介绍了找出活动的本地IP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
由于这个原因,我需要使用以下代码来查找本地IP地址:
I need to find out the local Ip address, for that reason I was using the following code:
IPHostEntry host;
string localIP = "";
host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
localIP = ip.ToString();
break;
}
}
return localIP;
我发现,当一台PC的AddressFamily.InterNetwork
具有多个IP时,我总是得到第一个IP.但是,我找不到任何属性来查找活动IP.
I find out that when a PC has more than one IP with AddressFamily.InterNetwork
I get always the first one. However I can't find any property to find out the active IP.
如何获取正确的IP?
谢谢小费!
推荐答案
static string GetActiveIP()
{
string ip = "";
foreach (NetworkInterface f in NetworkInterface.GetAllNetworkInterfaces())
{
if (f.OperationalStatus == OperationalStatus.Up)
{
IPInterfaceProperties ipInterface = f.GetIPProperties();
if (ipInterface.GatewayAddresses.Count > 0)
{`enter code here`
foreach (UnicastIPAddressInformation unicastAddress in ipInterface.UnicastAddresses)
{
if ((unicastAddress.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) && (unicastAddress.IPv4Mask.ToString() != "0.0.0.0"))
{
ip = unicastAddress.Address.ToString();
break;
}
}`enter code here`
}
}
}
return ip;
}
这篇关于找出活动的本地IP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文