c# 多网卡 由【网络适配器名】获取网卡信息,IP
程序员文章站
2022-05-10 13:07:00
...
c# 多网卡 由【网络适配器名】获取网卡信息,IP
多网卡电脑中,网络适配器的名字 多样化!
- 项目中需要,根据网络适配器 名字 获取 单个网卡的IP:
using System.Net.NetworkInformation;
class Program
{
static void Main(string[] args)
{
Console.WriteLine(GetIPv4AddressByAdapterName("以太网2"));
Console.ReadLine();
}
private static string GetIPv4AddressByAdapterName(string adapterName)
{
NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface adapter in adapters)
{
if (adapter.Name == adapterName)
{
UnicastIPAddressInformationCollection unicastIPAddressInformation = adapter.GetIPProperties().UnicastAddresses;
foreach (var item in unicastIPAddressInformation)
{
if (item.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
return item.Address.ToString();
}
}
}
}
return string.Empty;
}
}