2010-10-24 121 views
-1

我想获取用户的IP地址(登录的用户将在那里运行应用程序在那里有本地PC上的用户上下文),但我们环境中的许多PC有多个网卡已经由VMWare Workstation添加,我想排除这些类型的桥接连接,并只在PC上显示“主”NIC。用户多个网卡的IP地址

以下函数将获得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

为什么对5岁的问题进行投票? – Lima 2015-11-17 00:36:28

回答

2

你总是可以使用

If ipAddress.ToString().StartsWith("172.16) Then 
    ' Now you've got a match 
    ipAddress = tmpAddr(i).ToString() 
End If 

当然,我的代码是不好的,因为你所呼叫的ToString()两次,这可能是一个拖累业绩如果有很多地址需要解析,那么您可能需要稍微修改它...

+0

完美地工作,我将赋值更改为tmpAddr,并检查了tmpAddr是否以172.16开头,然后如果true赋给tmpAddr以ipAddress。感谢您的快速帮助。 – Lima 2010-10-24 05:03:43

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