从返回的多个IP地址中确定以太网适配器本地连接IPv4地址
本文关键字:地址 以太网 适配器 本地连接 IPv4 IP 返回 | 更新日期: 2023-09-27 17:49:17
我使用下面的代码来检索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。 * * * 。 * * *
您是否正在寻找属性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)
假设只有一个感兴趣的连接与一个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
。
{
var sb = new StringBuilder();
NetworkInterface[] networkInterfaces =
NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface network in networkInterfaces)
{
IPInterfaceProperties properties = network.GetIPProperties();
foreach (UnicastIPAddressInformation address in
properties.UnicastAddresses)
{
if (address.Address.AddressFamily != AddressFamily.InterNetwork) // We're only interested in IPv4 addresses for now
continue;
if (IPAddress.IsLoopback(address.Address)) // Ignore loopback addresses (e.g., 127.0.0.1)
continue;
if (network.OperationalStatus == OperationalStatus.Up)
sb.AppendLine(address.Address.ToString() + " (" + network.Name + ")");
}
}
Console.WriteLine(sb.ToString());
}