2010-05-25 125 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