查找通过哪个网络设备用户连接到Internet

时间:2011-04-01 22:25:47

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

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

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

但我的问题是如何通过用户连接到互联网来获取默认一个(以太网适配器)?

我需要更改一些默认设置(通过用户连接到Internet )适配器。设置我通过注册表更改,所以我可以为每个网络接口添加相同的设置,但这可能会导致问题,然后没有任何意义:D

任何人都可以帮忙吗?谢谢! ;)

编辑:

现在我已经完成了下面的代码,所以如果这可以帮助其他人...... :) 但如果有人有击球手解决方案或更可靠,那么请发送

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

2 个答案:

答案 0 :(得分:1)

这会给你一些提示吗?

Identifying active network interface

答案 1 :(得分:-1)

我将你的代码移植到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());
                    }
                }
            } 
        }
    }