我想获取用户的IP地址(登录的用户将在本地PC上的用户上下文中运行应用程序),但是我们环境中的许多PC都有多个已由VMWare Workstation添加的NIC,I想要排除这些类型的桥接连接,只显示PC上的“主要”NIC。
以下函数将获取IPv4地址,但是在我的测试PC上,它将返回桥接连接,而不是面向NIC的网络的IP地址。
Shared Function GetIP(ByVal computerName As String) As String
'Dim ipEntry As IPHostEntry = Dns.GetHostEntry(computerName)
'Dim tmpAddr As IPAddress() = ipEntry.AddressList
Dim ipAddress As String = ""
'Dim i As Integer = 0
'Do While i < tmpAddr.Length
' If tmpAddr(i).AddressFamily = Sockets.AddressFamily.InterNetwork Then
' ipAddress = tmpAddr(i).ToString
' End If
' i += 1
'Loop
Dim ipentry As System.Net.IPHostEntry = System.Net.Dns.GetHostEntry("")
For i As Integer = 0 To ipentry.AddressList.Count - 1
ipAddress = System.Net.Dns.GetHostEntry("").AddressList(i).ToString
Next
Return ipAddress
End Function
我的用户混合使用DHCP和静态地址,因此无法将NIC限制为这些连接类型中的任何一种。我们倾向于拥有172.16.x.x的IP范围,所以有没有办法修改上面的函数,以便它只返回172.16.x.x的地址?
非常感谢您的协助。
谢谢,
马特
答案 0 :(得分:2)
您可以随时使用
If ipAddress.ToString().StartsWith("172.16) Then
' Now you've got a match
ipAddress = tmpAddr(i).ToString()
End If
当然,我的代码很糟糕,因为你要调用.ToString()两次,如果要解析很多地址,这可能会导致性能下降,所以你可能想稍微修改它......
答案 1 :(得分:0)
这可能有所帮助,或提供其他方法的提示
'Imports System.Net
'get all IP addresses on PC
Dim IPs As System.Net.IPHostEntry = Dns.GetHostEntry("")
'look for IPv4 that starts with 172.16
For Each IPaddr As System.Net.IPAddress In IPs.AddressList
'check for IPv4
If IPaddr.AddressFamily = Net.Sockets.AddressFamily.InterNetwork Then
If Not System.Net.IPAddress.IsLoopback(IPaddr) Then 'not loopback
If IPaddr.ToString.StartsWith("172.16") Then
'found it, see if matching gateway
Dim adapters() As NetworkInformation.NetworkInterface
adapters = NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()
For Each adapter As NetworkInformation.NetworkInterface In adapters
Dim adapterProperties As NetworkInformation.IPInterfaceProperties = adapter.GetIPProperties()
Dim addresses As NetworkInformation.GatewayIPAddressInformationCollection = adapterProperties.GatewayAddresses
If addresses.Count > 0 Then
Dim addr As NetworkInformation.GatewayIPAddressInformation
For Each addr In addresses
If addr.Address.ToString.StartsWith("172.16") Then
Stop
End If
Next addr
End If
Next adapter
End If
End If
End If
Next