VB调用GetAdaptersInfo 的正确方法

阅读更多
  网上的教程没有一个能在多网卡或多IP下用的,总是在 CopyMemory 时程序崩溃,没办法,只好自己找原因了,几次崩溃之后,终于找到了原因,在用 0& 调用后返回的AdapterInfoSize 在多网卡时,长度超过了IP_ADAPTER_INFO 结构,而所有教程都是用AdapterInfoSize 调用的CopyMemory ,所以程序崩溃就是必然了,找到问题,解决就相对简单了,用 sizeof(IP_ADAPTER_INFO)就对了,可惜VB 没有这个运算符,只好自己定义一个常量来代替,完整代码如下,希望能帮助一些人。
Public Const MAX_ADAPTER_NAME_LENGTH = 260
Public Const MAX_ADAPTER_ADDRESS_LENGTH = 8
Public Const MAX_ADAPTER_DESCRIPTION_LENGTH = 132
Public Const IP_ADAPTER_INFO_LENGTH = 640
Type IP_ADDR_STRING
            Next As Long
            IpAddress As String * 16
            IpMask As String * 16
            Context As Long
End Type
Type IP_ADAPTER_INFO
            Next As Long
            ComboIndex As Long
            AdapterName As String * MAX_ADAPTER_NAME_LENGTH
            Description As String * MAX_ADAPTER_DESCRIPTION_LENGTH
            AddressLength As Long
            Address(MAX_ADAPTER_ADDRESS_LENGTH - 1) As Byte
            Index As Long
            Type As Long
            DhcpEnabled As Long
            CurrentIpAddress As Long
            IpAddressList As IP_ADDR_STRING
            GatewayList As IP_ADDR_STRING
            DhcpServer As IP_ADDR_STRING
            HaveWins As Byte
            PrimaryWinsServer As IP_ADDR_STRING
            SecondaryWinsServer As IP_ADDR_STRING
            LeaseObtained As Long
            LeaseExpires As Long
End Type
Public Declare Function GetAdaptersInfo Lib "iphlpapi.dll" (IpAdapterInfo As Any, pOutBufLen As Long) As Long
Private Declare Sub CopyMemory Lib "kernel32.dll" Alias "RtlMoveMemory" (ByRef Destination As Any, ByRef Source As Any, ByVal Length As Long)
Public Function GetewayIP() As String
    Dim AdapterInfoSize As Long
    Dim AdapterInfo As IP_ADAPTER_INFO
    Dim AdapterInfoBuffer() As Byte
    Dim ptr1 As Long
   
    AdapterInfoSize = 0
    Call GetAdaptersInfo(ByVal 0&, AdapterInfoSize)
    ReDim AdapterInfoBuffer(AdapterInfoSize - 1)
    If 0 = GetAdaptersInfo(AdapterInfoBuffer(0), AdapterInfoSize) Then
        ptr1 = VarPtr(AdapterInfoBuffer(0))
        Do While (ptr1 <> 0)
            CopyMemory AdapterInfo, ByVal ptr1, IP_ADAPTER_INFO_LENGTH
            If InStr(AdapterInfo.GatewayList.IpAddress, Chr(0)) > 6 Then
                GetwayIP = Left(AdapterInfo.GatewayList.IpAddress, InStr(AdapterInfo.GatewayList.IpAddress, Chr(0)) - 1)
                Exit Function
            End If
            ptr1 = AdapterInfo.Next
        Loop
    End If
End Function


你可能感兴趣的:(VB)