查找用户通过哪个网络设备连接到互联网
使用下面的代码,我将获得机器上启用和运行的所有网络接口。
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
Using the code below I will get all network interfaces which are enabled and functional on the machine.
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
But my problem is how to get the default one, the one(ethernet adapter) through which user is connected to internet?
I need to change some settings of default(through which user is connected to internet) adapter. settings I change through registry so I could sample add same settings for each network interface but that could cause problems and makes no point then.
EDITED:
For now I have done like code below, so if this can help someone other, but if someone has a better solution or more reliable then send please.
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这会给你一些提示吗?
识别活动网络接口
Will this give you some hints?
Identifying active network interface
我将你的代码移植到了 c#,希望你不介意
i ported your code to c#, i hope you don' t mind