Find through which network device user is connected to internet
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
Thanks Thomas-Li and this post
Will this give you some hints?
Identifying active network interface
i ported your code to c#, i hope you don' t mind
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());
}
}
}
}
}
精彩评论