【问题标题】:Find through which network device user is connected to internet查找用户通过哪个网络设备连接到互联网
【发布时间】:2011-04-01 22:25:46
【问题描述】:

使用下面的代码,我将获得机器上已启用并正常运行的所有网络接口。

Private netIntrfc As NetworkInterface() = NetworkInterface.GetAllNetworkInterfaces()
For i As Integer = 0 To netIntrfc.Length - 1
  If netIntrfc(i).OperationalStatus = OperationalStatus.Up Then
    netDevicesList.Items.Add(netIntrfc(i).Name.ToString)
  End If
Next

但我的问题是如何获得 默认 一个,即用户连接到互联网的那个(以太网适配器)?

我需要更改默认(用户连接到互联网)适配器的一些设置。我通过注册表更改设置,因此我可以为每个网络接口添加相同的设置,但这可能会导致问题并且没有意义。

已编辑:

现在我已经完成了下面的代码,所以如果这可以帮助其他人,但如果有人有更好的解决方案或更可靠,请发送。

Dim u As UdpClient = New UdpClient(System.Net.Dns.GetHostName, 1)
Dim localAddr As IPAddress = CType(u.Client.LocalEndPoint, IPEndPoint).Address

Private netIntrfc As NetworkInterface() = NetworkInterface.GetAllNetworkInterfaces()
For i As Integer = 0 To netIntrfc.Length - 1
  If netIntrfc(i).OperationalStatus = OperationalStatus.Up Then
    For Each uni As NetworkInformation.UnicastIPAddressInformation In ipProps.UnicastAddresses
      If uni.Address.ToString = localAddr.ToString Then
        netDevicesList.Items.Add("DEFAULT: " & netIntrfc(i).Name.ToString)
        DEFDEVID = netIntrfc(i).Id.ToString
      End If
    Next
    netDevicesList.Items.Add(netIntrfc(i).Name.ToString)
  End If
Next

感谢Thomas-Lithis post

【问题讨论】:

  • 这会给你一些提示吗? stackoverflow.com/questions/359596/…
  • 是的,这对我有帮助 :) 希望它能正常工作我没有太多资源来测试它,但至于我在我的电脑上用 3 个以太网卡和一个无线它工作正常 :) 谢谢。你可以发布作为答案,所以我接受你;)

标签: c# vb.net visual-studio networking network-programming


【解决方案1】:

这会给你一些提示吗?

Identifying active network interface

【讨论】:

    【解决方案2】:

    我将你的代码移植到 c#,希望你不介意

        static void Main(string[] args)
        {
            UdpClient u = new UdpClient(System.Net.Dns.GetHostName(), 1);
            IPAddress localAddr = (u.Client.LocalEndPoint as IPEndPoint).Address;
            NetworkInterface[] netIntrfc  = NetworkInterface.GetAllNetworkInterfaces();
            for (int i = 0; i < netIntrfc.Length - 1; i++)
            {
                if (netIntrfc[i].OperationalStatus == OperationalStatus.Up) 
                {
                    IPInterfaceProperties ipProps = netIntrfc[i].GetIPProperties();
                    foreach (UnicastIPAddressInformation uni in ipProps.UnicastAddresses) 
                    {
                        if (uni.Address.ToString() == localAddr.ToString()) 
                        {
                            Console.WriteLine("DEFAULT: " + netIntrfc[i].Name.ToString());
                            Console.WriteLine(netIntrfc[i].Id.ToString());
                        }
                    }
                } 
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-09
      • 1970-01-01
      • 2017-09-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多