我在同步“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()); } } } }
我该如何解决这个问题?
解决方法
代码中的问题是您不使用关联的IP地址
对于给定的适配器.而不是将所有IP地址匹配到每个适配器
仅使用与当前适配器关联的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()); } } }
原文地址:https://www.jb51.cc/csharp/93250.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。