【问题标题】:Get IP address and adapter description using C#使用 C# 获取 IP 地址和适配器描述
【发布时间】:2012-10-21 21:54:04
【问题描述】:

我在同步“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 :)
  • 当我们有多个互联网适配器时会出现问题..
  • 查看“cmd > ipconfig /all”观察消息框会重复ip地址s
  • 消息框只能预览您计算机的适配器

标签: c# networking ip-address


【解决方案1】:

您的代码中的问题是您没有使用关联的 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());
        }
    }
}

【讨论】:

  • 这一定是解决方案,就这样+1
  • **@Hans : 我有 2 个问题要问你第一个问题,我们如何防止 Loopback 地址在消息框中预览? 2 我怎样才能接受你的回答?大声笑**
  • @RoiseEscalera:您可以通过在 if 语句中添加以下条件来过滤环回地址:ip.Address.Equals(IPAddress.Loopback) == false。要接受我的回答,请点击投票箭头下方的空心复选(勾号)符号。
猜你喜欢
  • 1970-01-01
  • 2013-01-20
  • 1970-01-01
  • 2023-04-08
  • 2022-03-03
  • 2018-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多