问题
I am trying to develop a generic VB.NET based application that will return me the Ethernet IP Address of the local machine. I have referred to several questions discussed here for getting the IP Address of the machine and found a few good suggestions.
The problem I am facing is, when I run this application, it returns me the IP Address of both WiFi and Ethernet. When I run this application on somebody else's machine, I unable to tell which IP Address belongs to which interface. I am interested in Ethernet IP Address only.
Any suggestions ??
Here is the function that returns the list of IP Addresses.
Function getIP() As String
Dim ips As System.Net.IPHostEntry = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName)
For Each ip In ips.AddressList
If (ip.AddressFamily = System.Net.Sockets.AddressFamily.InterNetwork) Then
MessageBox.Show(ip.ToString)
Return ip.ToString
End If
Next
Return Nothing
End Function
回答1:
Rather than getting IP addresses via an IPHostEntry
, you can enumerate through the network adapters, then get the IP addresses from each adapter.
A NetworkInterface provides its type via the NetworkInterfaceType
property. For ethernet adapters, this returns Ethernet
. For a wireless adapter, the documentation doesn't specify, but it returned Wireless80211
for me.
Sample code:
Imports System.Net.NetworkInformation
Public Class Sample
Function GetIP() As String
Dim networkInterfaces() As NetworkInterface
networkInterfaces = NetworkInterface.GetAllNetworkInterfaces()
For Each networkInterface In networkInterfaces
If networkInterface.NetworkInterfaceType = NetworkInterfaceType.Ethernet Then
For Each address In networkInterface.GetIPProperties().UnicastAddresses
If address.Address.AddressFamily = Net.Sockets.AddressFamily.InterNetwork Then
Return address.Address.ToString()
End If
Next address
End If
Next networkInterface
Return Nothing
End Function
End Class
Or, if you want a slightly more concise version, you could use LINQ (equivalent to the code above):
Function GetIP() As String
Return (
From networkInterface In networkInterface.GetAllNetworkInterfaces()
Where networkInterface.NetworkInterfaceType = NetworkInterfaceType.Ethernet
From address In networkInterface.GetIPProperties().UnicastAddresses
Where address.Address.AddressFamily = Net.Sockets.AddressFamily.InterNetwork
Select ip = address.Address.ToString()
).FirstOrDefault()
End Function
来源:https://stackoverflow.com/questions/27843591/how-to-distinguish-between-ethernet-and-wifi-ip-addresses-using-vb-net