我正在使用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地址?
答案 0 :(得分: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