2010-05-25 90 views
1

如何返回VB.Net中的IPv4地址?VB.Net返回IPv4地址

例如。 192.168.1.5

+0

你想要的IP地址给定主机名?或传入请求的IP地址?或本地计算机的IP地址(可能有多个地址)? – Jason 2010-05-25 21:31:10

回答

0
Dim myClientMachineAddressList As IPHostEntry = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()) 
Dim myClientMachineIP As String = myClientMachineAddressList.AddressList(0).ToString() 

编辑:

那么你可以使用IPAddress.AddressFamily找出IP familly类型。

+1

将返回IPv6,如果它在那里(我认为) – PostMan 2010-05-25 21:19:37

+0

@PostMan - 感谢评论我修改了帖子。 – Cicik 2010-05-25 21:26:50

4

像这样的事情

Public Function GetIpV4() As String 

    Dim myHost As String = Dns.GetHostName 
    Dim ipEntry As IPHostEntry = Dns.GetHostEntry(myHost) 
    Dim ip As String = "" 

    For Each tmpIpAddress As IPAddress In ipEntry.AddressList 
    If tmpIpAddress.AddressFamily = Sockets.AddressFamily.InterNetwork Then 
     Dim ipAddress As String = tmpIpAddress.ToString 
     ip = ipAddress 
     exit for 
    End If 
    Next 

    If ip = "" Then 
    Throw New Exception("No 10. IP found!") 
    End If 

    Return ip 

End Function 
+0

+1写得不错:) – Cicik 2010-05-25 21:30:30

1

尽我所能做到的是,将只使用阵列功能和lambda表达式,很干净仅返回IPv4地址 :

Public Function GetHostEntryIPv4(ByVal addr As String) As IPHostEntry 

    Dim ipHostInfo As IPHostEntry = Dns.GetHostEntry(addr) 

    If Not IsNothing(ipHostInfo) Then 
     ipHostInfo.AddressList = Array.FindAll(ipHostInfo.AddressList, Function(n As IPAddress) n.AddressFamily = AddressFamily.InterNetwork) 
    End If 

    GetHostEntryIPv4 = ipHostInfo 

End Function