c# - 如何获取网络接口(interface)及其正确的 IPv4 地址?

标签 c# ip-address network-interface

我需要知道如何使用他们的 IPv4 获取所有网络接口(interface)地址。 或者只是无线和以太网。

要获取所有网络接口(interface)的详细信息,我使用这个:

foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces()) {
    if(ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 ||
       ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet) {

        Console.WriteLine(ni.Name);
    }
}

并获取计算机的所有托管 IPv4 地址:

IPAddress [] IPS = Dns.GetHostAddresses(Dns.GetHostName());
foreach (IPAddress ip in IPS) {
    if (ip.AddressFamily == AddressFamily.InterNetwork) {

        Console.WriteLine("IP address: " + ip);
    }
}

但是如何获取网络接口(interface)及其正确的 ipv4 地址呢?

最佳答案

foreach(NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
{
   if(ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 || ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
   {
       Console.WriteLine(ni.Name);
       foreach (UnicastIPAddressInformation ip in ni.GetIPProperties().UnicastAddresses)
       {
           if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
           {
               Console.WriteLine(ip.Address.ToString());
           }
       }
   }  
}

这应该可以满足您的需求。 ip.Address 是您想要的 IP 地址。

关于c# - 如何获取网络接口(interface)及其正确的 IPv4 地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9855230/

相关文章:

c# - System.Security.Cryptography 中不存在 MD5 类

php - 使用 php 获取用户 ip 地址的最可靠方法?

c# - 在当前子网中找到免费 IP 地址的最简单方法?

linux - 通过网络接口(interface)发送数据包(icmp 或其他),绕过路由表

hadoop - Spark : Connection refused webapp proxy on yarn

linux - 更改两个 EC2 实例之间的主弹性网络接口(interface) (ENI)

c# - 如何从嵌套在数组中的数组中更新项目

c# - 模拟一段时间内的高CPU使用率

c# - 如何使用查询字符串中的数据重写 Azure 图像 URL

Java getHostAddress() 返回 VirtualBox IPv4 地址