如何获得当前使用的网络适配器

问题描述 投票:0回答:1

现在,我正在尝试在机器上的多个网络适配器中使用网络适配器,以便获取网络适配器的IP地址,mac地址和适配器名称。但是我没有运气。我找到的解决方案是Get current network adapter in use。我不认为它适用于.Net框架项目,但适用于ASP.NET Core。

我的代码在下面。

public void GetIpAndMacAddress()
{
    foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
    {
        // Only consider Ethernet network interfaces
        if (nic.NetworkInterfaceType == NetworkInterfaceType.Ethernet &&
            nic.OperationalStatus == OperationalStatus.Up)
        {
            IPInterfaceProperties adapterProperties = nic.GetIPProperties();
            foreach (var ip in adapterProperties.UnicastAddresses) 
            {
                if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                    IPAddress = ip.Address.ToString();
            }
            string hexMac = nic.GetPhysicalAddress().ToString(),
                   regex = "(.{2})(.{2})(.{2})(.{2})(.{2})(.{2})",
                   replace = "$1:$2:$3:$4:$5:$6";
            IPv4InterfaceProperties p = adapterProperties.GetIPv4Properties();

            netAdapterName = nic.Name;
            MACAddress = Regex.Replace(hexMac, regex, replace);
            return;
        }
    }
}
c# ip-address mac-address
1个回答
0
投票

以下内容应为您提供帮助。

NetworkInterface[] networks = NetworkInterface.GetAllNetworkInterfaces();

var activeAdapter = networks.First(x=> x.NetworkInterfaceType != NetworkInterfaceType.Loopback
                    && x.NetworkInterfaceType != NetworkInterfaceType.Tunnel
                    && x.OperationalStatus == OperationalStatus.Up 
                    && x.Name.StartsWith("vEthernet") == false);

搜索是基于消除既不是Loopback(通常用于测试)也不是Tunnel(通常用于专用网络之间的安全连接)的网络适配器。运行状态可确保网络接口已启动并且能够传输数据包。 “ vEthernet”是Windows通常用于Hyper-V Virtual Network Adapters

的命名约定
© www.soinside.com 2019 - 2024. All rights reserved.