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

Roi*_*era 6 c# networking ip-address

我在同步"IP地址和描述"时出现问题.

目标是这样的:

获取IP地址和描述是什么?

例:

| Atheros Azx1234 Wireless Adapter |

|192.168.1.55                      |
Run Code Online (Sandbox Code Playgroud)

但结果不是我的预期......

这是我的代码随意尝试...

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());
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我该如何解决这个问题?

Han*_*ans 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());
        }
    }
}
Run Code Online (Sandbox Code Playgroud)