如何获取连接到 Internet 的适配器的 IP 和 MAC 地址?

How to get IP and MAC addresses of the adapter that connects to the Internet?

当使用 System.Net.Dns.GetHostAddresses(System.Net.Dns.GetHostName()) 获取 IP 地址和

    private System.Net.NetworkInformation.PhysicalAddress GetMacAddress()
    {
        foreach (System.Net.NetworkInformation.NetworkInterface nic in System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces())
        {
            // Only consider Ethernet network interfaces
            if (nic.NetworkInterfaceType == System.Net.NetworkInformation.NetworkInterfaceType.Ethernet &&
                nic.OperationalStatus == System.Net.NetworkInformation.OperationalStatus.Up)
            {
                return nic.GetPhysicalAddress();
            }
        }
        return null;
    }

要获取 MAC 地址,我获取了所有地址。有没有办法只获取实际连接到网络的适配器和 IP?

通过上述调用,我还获得了属于虚拟适配器的 IP 和 MAC,例如由 VMWare 创建的。

问候 海梅

作为一个好方法,我正在寻找具有网关设置的网卡。这适用于我的情况:

    private static IEnumerable<System.Net.NetworkInformation.NetworkInterface> GetAllNetworkInterfaces(IEnumerable<System.Net.NetworkInformation.NetworkInterfaceType> excludeTypes)
    {
        var all = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces().Where(nic => nic.GetIPProperties().GatewayAddresses.Any() && nic.OperationalStatus == System.Net.NetworkInformation.OperationalStatus.Up);
        var exclude = all.Where(i => excludeTypes.Contains(i.NetworkInterfaceType));
        return all.Except(exclude);
    }

然后,像这样使用它:

                var nic = GetAllNetworkInterfaces(new[] { System.Net.NetworkInformation.NetworkInterfaceType.Tunnel, System.Net.NetworkInformation.NetworkInterfaceType.Loopback });
                txtRegistro.AppendText($"Local IP -> {string.Join(", ", nic.SelectMany(n => n.GetIPProperties().UnicastAddresses).Where(i => i.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork).Select(i => i.Address.ToString()))}\r\n");
                txtRegistro.AppendText($"MAC Address -> {string.Join(", ", nic.Select(a => string.Join(":", a.GetPhysicalAddress().GetAddressBytes().Select(b => b.ToString("X2")))))}\r\n\r\n");

使用上面的代码,只要连接的路由器提供网关,我就会得到哪个 NIC 连接到网络(LAN 或 WAN)。

此致

海梅