确定从多个IP地址返回的以太网适配器本地连接IPv4地址

时间:2014-03-10 21:56:15

标签: c# .net ip-address ipv4

我使用以下代码检索IPv4地址(以太网适配器本地连接)。但是我看到代码返回了多个地址。 有没有办法说明哪个返回的地址是以太网适配器本地连接IP地址?

    List<string> all = new List<string>();
    string hostName = Dns.GetHostName();
    IPHostEntry hostEntry = Dns.GetHostEntry(hostName);
    foreach (IPAddress address in hostEntry.AddressList)
    {
        if (address.AddressFamily == AddressFamily.InterNetwork)
            all.Add(address.ToString() + "\n");
    }

    dataGridView2.DataSource = all.Select(x => new { Value = x }).ToList();
}

目前上面的代码返回3个值

  • 172.20。的 * ** ***
  • 192.168。的 * ** 即可。 * **
  • 192.168。的 * ** 即可。 * **

以太网适配器本地连接IP地址为172.20。 * ** ***

2 个答案:

答案 0 :(得分:2)

您是否正在寻找属性NetworkInterfaceType和AddressFamily?

的连接
foreach (var i in NetworkInterface.GetAllNetworkInterfaces())
{
   Console.WriteLine("{0} ({1})", i.Name, i.NetworkInterfaceType);
   foreach (var a in i.GetIPProperties().UnicastAddresses)
   {
      Console.WriteLine("      {0} ({1})", a.Address, a.Address.AddressFamily);
   }
}

这会给你举个例子:

Local Area Connection (Ethernet) (InterNetworkV6) 169.254.171.253 (InterNetwork)

答案 1 :(得分:0)

假设只有一个感兴趣的连接与一个IPv4地址,请考虑以下内容:

var connectionName = "Ethernet Adapter Local Area Connection";
var connection =
    NetworkInterface.GetAllNetworkInterfaces().FirstOrDefault(
        ni => ni.Name == connectionName);
if (connection != null)
{
    Console.WriteLine("Connection \"{0}\" found.", connectionName);

    // Use a regex to focus on the IPv4 address and ignore the IPv6 address if
    // present.
    var ipV4Regex = new Regex("(?<IPv4Address>([0-9]{1,3}\\.){3}[0-9]{1,3})");
    var unicastAddresses = connection.GetIPProperties().UnicastAddresses;
    var ipV4Address =
        unicastAddresses.FirstOrDefault(
            ua => ipV4Regex.Match(ua.Address.ToString()).Success);

    if (ipV4Address != null)
        Console.WriteLine("IPv4 address {0} found.", ipV4Address.Address);
    else
        Console.WriteLine("IPv4 address not found.");
}
else
{
    Console.WriteLine("Connection \"{0}\" not found.", connectionName);
}

为了清晰起见,我使用了控制台输出,但您应该发现这适用于分配dataGridView2.DataSource