我在同步“IP地址和说明”时出现问题。
目标是:
获取IP地址以及描述是什么?
示例:
| Atheros Azx1234 Wireless Adapter |
|192.168.1.55 |
但结果并非我的预期...
这是我的代码随时可以尝试...
private void button1_Click(object sender, EventArgs e)
{
NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
IPHostEntry host;
host = Dns.GetHostEntry(Dns.GetHostName());
foreach (NetworkInterface adapter in interfaces)
{
foreach (IPAddress ip in host.AddressList)
{
if ((adapter.OperationalStatus.ToString() == "Up") && // I have a problem with this condition
(ip.AddressFamily == AddressFamily.InterNetwork))
{
MessageBox.Show(ip.ToString(), adapter.Description.ToString());
}
}
}
}
如何解决此问题?
答案 0 :(得分:12)
代码中的问题是您不使用关联的IP地址 对于给定的适配器。而不是将所有IP地址匹配到每个适配器 仅使用与当前适配器关联的IP地址:
NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (var adapter in interfaces)
{
var ipProps = adapter.GetIPProperties();
foreach (var ip in ipProps.UnicastAddresses)
{
if ((adapter.OperationalStatus == OperationalStatus.Up)
&& (ip.Address.AddressFamily == AddressFamily.InterNetwork))
{
Console.Out.WriteLine(ip.Address.ToString() + "|" + adapter.Description.ToString());
}
}
}