如何获取网络接口及其正确的IPv4地址?

Mur*_*sli 61 c# ip-address network-interface

我需要知道如何使用其IPv4地址获取所有网络接口.或者只是无线和以太网.

要获取所有网络接口详细信息,我使用此:

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

        Console.WriteLine(ni.Name);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

        Console.WriteLine("IP address: " + ip);
    }
}
Run Code Online (Sandbox Code Playgroud)

但是如何获得网络接口及其正确的ipv4地址?

小智 101

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

这应该可以满足您的需求.ip.Address是您想要的IPAddress.

  • 这可以使用[this](https://goo.gl/rmP8RO)Linq查询进行简化. (7认同)
  • @Felk谢谢,这是原来的网址https://gist.github.com/anonymous/ff82643c9a004281544a (3认同)

Mc_*_*paz 9

与 lamda 的一行:

using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Net.NetworkInformation;

var ipV4s = NetworkInterface.GetAllNetworkInterfaces()
    .Select(i => i.GetIPProperties().UnicastAddresses)
    .SelectMany(u => u)
    .Where(u => u.Address.AddressFamily == AddressFamily.InterNetwork)
    .Select(i => i.Address);
Run Code Online (Sandbox Code Playgroud)