1

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

例如。192.168.1.5

4

3 回答 3

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
于 2010-05-25T21:24:36.853 回答
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
于 2011-01-25T02:47:29.273 回答
0
Dim myClientMachineAddressList As IPHostEntry = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName())
Dim myClientMachineIP As String = myClientMachineAddressList.AddressList(0).ToString()

编辑:

然后您可以使用IPAddress.AddressFamily找出 IP 家族类型。

于 2010-05-25T21:15:20.653 回答