1

我正在使用 VBScript 使用 Win32_PingStatus 检索远程计算机的地址,如下所示:

dnsServer = "myComputerName"
Set objWMIService = GetObject("winmgmts:\\.\root\cimv2")
colIpQuery = "Select * from Win32_PingStatus where Address='" + dnsServer + "' AND ResolveAddressNames=TRUE"
Set colIPAddrs = objWMIService.ExecQuery(colIpQuery)
For Each colIPAddr In colIPAddrs
    If CStr(colIpAddr.StatusCode) = 0 Then
        dnsServerIp = colIpAddr.ProtocolAddress
    End If
Next

这里的问题是,如果“myComputerName”正在运行 IPv6,colIpAddr.ProtocolAddress将始终只返回 IPv6 地址,但我需要 IPv4 地址。我无法禁用 IPv6、跳过 IPv6 地址等。有没有其他方法可以在不使用外部方法(ping、powershell 等)的情况下检索 IPv4 地址?

4

1 回答 1

0
' RETURN IPv4 ONLY
' ################################################
    Function getIPAddress(passedInt)
            On Error Resume Next
            Dim hostIPAddress, SQLQuery, strComputer, objWMIService, colItems
            SQLQuery = "SELECT * FROM Win32_NetworkAdapterConfiguration WHERE     MACAddress > '' AND IPEnabled = 'True'"
            strComputer = "."
            Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
            Set colItems = objWMIService.ExecQuery(SQLQuery)
        For Each objItem In colItems
            If IsArray( objItem.IPAddress ) Then
                If UBound( objItem.IPAddress ) = 0 Then
                    hostIPAddress = objItem.IPAddress(0)
                Else
                    hostIPAddress = "" & Join( objItem.IPAddress, "," )
                End If
            End If
        Next
        temp = split(hostIPAddress, ",")
        getIPAddress = temp(passedInt) ' temp(0) returns IPv4 Only, temp(1) retunrs IPv6 Only
    End function

我看了多个论坛,似乎没有人提到上述内容

从“Win32_NetworkAdapterConfiguration”返回“obj.IPAddress”用逗号分隔值,因此您可以使用 Split(stringToSplit, ",") 函数和数组中的引用索引 0 来返回 IPv4

'usage:
Dim temp, temp2
temp = getIPAddress(0)    ' temp = IPv4 address
temp2 = getIPAddress(1)   ' temp2 = IPv6 address
于 2018-11-01T20:34:56.443 回答