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

How to get current used network adapter

现在我正尝试在我的 machine 上的几个网络适配器中使用网络适配器,以便我可以获得网络适配器的 IP 地址、mac 地址和适配器名称。但我没有任何运气。 我找到的解决方案是 。 我认为它不是用于 .Net 框架项目,而是 ASP.NET 核心。

我的代码如下。

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 = ":::::";
            IPv4InterfaceProperties p = adapterProperties.GetIPv4Properties();

            netAdapterName = nic.Name;
            MACAddress = Regex.Replace(hexMac, regex, replace);
            return;
        }
    }
}

以下内容应该对您有所帮助。

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 (Commonly used for testing) or Tunnel(commonly used for secure connection between private networks). Operational Status ensures that the Network interface is up and is is able to transmit data packets. The "vEthernet" is naming convention commonly used by Windows for Hyper-V Virtual Network Adapters

的网络适配器