【问题标题】:VB.Net Return IPv4 AddressVB.Net 返回 IPv4 地址
【发布时间】:2010-05-25 21:13:02
【问题描述】:

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

例如。 192.168.1.5

【问题讨论】:

  • 您想要给定主机名的 IP 地址吗?还是传入请求的 IP 地址?还是本地机器的 IP 地址(可能有多个地址)?

标签: vb.net networking ip ipv4


【解决方案1】:

类似的东西

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

【讨论】:

    【解决方案2】:

    我能做的就是只返回 IPv4 地址 只使用数组函数和 lambda 表达式,非常干净:

    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
    

    【讨论】:

      【解决方案3】:
      Dim myClientMachineAddressList As IPHostEntry = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName())
      Dim myClientMachineIP As String = myClientMachineAddressList.AddressList(0).ToString()
      

      编辑:

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

      【讨论】:

      • 如果存在 IPv6 将返回(我认为)
      猜你喜欢
      • 2011-02-25
      • 2012-01-03
      • 1970-01-01
      • 2013-09-18
      • 2016-09-20
      • 2017-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多