加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 03:57:06 所属栏目:百科 来源:网络整理
导读:我在同步“IP地址和描述”时出现问题. 目标是这样的: 获取IP地址和描述是什么? 例: | Atheros Azx1234 Wireless Adapter ||192.168.1.55 | 但结果不是我的预期…… 这是我的代码随意尝试… private void button1_Click(object sender,EventArgs e){ Netwo
我在同步“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地址:
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());
        }
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读