3

VB6如何在不使用Winsock控件的情况下获取本地IP地址

我不想使用或不需要 Winsock 的原因是因为我的应用程序应该离线工作。

我对 VB6 有点陌生,我对这个主题的搜索失败了。我想我需要一些 WinAPI,任何指针或代码示例都会很明显。

4

2 回答 2

4

这是我喜欢使用的功能,不需要 API:

Public Function getIP()

Dim WMI     As Object
Dim qryWMI  As Object
Dim Item    As Variant

    Set WMI = GetObject("winmgmts:\\.\root\cimv2")

    Set qryWMI = WMI.ExecQuery("SELECT * FROM Win32_NetworkAdapterConfiguration " & _
                               "WHERE IPEnabled = True")

    For Each Item In qryWMI
      getIP = Item.IPAddress(0)
    Next

    Set WMI = Nothing
    Set qryWMI = Nothing

End Function
于 2012-12-07T15:13:22.980 回答
2

这是从这里获取的:VB Function to Find the IP Address

Private Declare Function GetIpAddrTable_API Lib "IpHlpApi" Alias "GetIpAddrTable" (pIPAddrTable As Any, pdwSize As Long, ByVal bOrder As Long) As Long

' Returns an array with the local IP addresses (as strings).
' Author: Christian d'Heureuse, www.source-code.biz
Public Function GetIpAddrTable()
   Dim Buf(0 To 511) As Byte
   Dim BufSize As Long: BufSize = UBound(Buf) + 1
   Dim rc As Long
   rc = GetIpAddrTable_API(Buf(0), BufSize, 1)
   If rc <> 0 Then Err.Raise vbObjectError, , "GetIpAddrTable failed with return value " & rc
   Dim NrOfEntries As Integer: NrOfEntries = Buf(1) * 256 + Buf(0)
   If NrOfEntries = 0 Then GetIpAddrTable = Array(): Exit Function
   ReDim IpAddrs(0 To NrOfEntries - 1) As String
   Dim i As Integer
   For i = 0 To NrOfEntries - 1
      Dim j As Integer, s As String: s = ""
      For j = 0 To 3: s = s & IIf(j > 0, ".", "") & Buf(4 + i * 24 + j): Next
      IpAddrs(i) = s
      Next
   GetIpAddrTable = IpAddrs
   End Function



' Test program for GetIpAddrTable.
Public Sub Test()
   Dim IpAddrs
   IpAddrs = GetIpAddrTable
   Debug.Print "Nr of IP addresses: " & UBound(IpAddrs) - LBound(IpAddrs) + 1
   Dim i As Integer
   For i = LBound(IpAddrs) To UBound(IpAddrs)
      Debug.Print IpAddrs(i)
      Next
   End Sub

我在我的机器上对其进行了测试,它产生了 2 个 IpAddr。我通常会认为第二个是我实际的。

于 2012-12-07T02:24:28.607 回答