C# · 12月 27, 2021

使用C#获取IP地址和适配器描述

我在同步“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)) { Message@R_51_2419@.Show(ip.ToString(),adapter.Description.ToString()); } } }}

我该如何解决这个问题?

解决方法 代码中的问题是您不使用关联的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()); } }}