【问题标题】:How to get current used network adapter如何获取当前使用的网络适配器
【发布时间】:2020-03-28 23:33:10
【问题描述】:

现在我正在尝试在我的机器上的几个网络适配器中使用网络适配器,以便我可以获得网络适配器的 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;
        }
    }
}

【问题讨论】:

  • “使用中”是什么意思?
  • @John_ReinstateMonica,感谢您的关注,这意味着我当前使用的网络适配器用于连接互联网。

标签: c# ip-address mac-address


【解决方案1】:

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

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

【讨论】:

  • 感谢您的回复,我会检查并通知您
  • 我想这是我想要的,你能解释一下搜索词吗?
  • @JSGuru 我已经用简短的描述更新了答案。希望有所帮助
  • 您好 Anu Viswan,感谢您的帮助。
猜你喜欢
  • 2023-03-31
  • 2012-06-24
  • 2023-03-25
  • 2023-04-08
  • 2017-07-27
  • 1970-01-01
  • 2015-08-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多