Using VBScript to determine what subnet a computer is in

I am tryign to use VBScript to determine what subnet a computer is in. I have the attached snippets of code that return the following;

strIP =
strSubnetMak =
strMask 24

What I need to do, is match it to a network address ( that I am using a separate piece of code to pull from AD

Any thoughts on a easy, and consistent way to do this (there will be around subnets / network addresses to match against, of all different sizes)

Dim arrOctets
  Dim strBinIP, strBinMask, strIPBit, strMaskBit, strBinNetwork, strMaskLength
  Dim intOctet, i, j
On Error Resume Next
Const HKEY_LOCAL_MACHINE = &H80000002
Set oReg=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" &_
Set WSHShell = CreateObject("Wscript.Shell")
strKeyPath = "SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces\"
oReg.EnumKey HKEY_LOCAL_MACHINE, strKeyPath, arrSubKeys
For Each subkey In arrSubKeys
    DHCPAddress = WSHShell.RegRead("HKLM\" & strKeyPath & subkey & "\DhcpIPAddress")	
    If DHCPAddress <> "" And Left(DHCPAddress,3) <> "169" Then
      strIP = DHCPAddress    
		strMask  = WSHShell.RegRead("HKLM\" & strKeyPath & subkey & "\DhcpSubnetMask")
		MaskLength strMask
    End If
		WScript.Echo strIP
		WScript.Echo strMask
		WScript.Echo strMaskLength		
Function MaskLength(strMask)
  ' Converts an subnet mask into a mask length in bits
  Dim arrOctets
  Dim intOctet, intMaskLength, i, j
  arrOctets = Split(strMask, ".")
  For i = 0 To UBound(arrOctets)
    intOctet = CInt(arrOctets(i))
    For j = 0 To 7
      If intOctet And (2^(7 -j)) Then
        intMaskLength = intMaskLength + 1
      End If
 MaskLength = intMaskLength
strMaskLength = intMaskLength
'WScript.Echo intMaskLength
End Function

Open in new window

Who is Participating?
grayeConnect With a Mentor Commented:
You might consider using Windows Management Instrumentation (WMI) to look into the Win32_NetworkAdapterConfiguration for the IP and Subnet.   Below is a trivial example...
Your function to convert the Subnet into the "class-less" numbering format looks fine

strComputer = "." 
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2") 
Set colItems = objWMIService.ExecQuery( _
    "SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True",,48) 
For Each objItem in colItems 
    Wscript.Echo "-----------------------------------"
    Wscript.Echo "Win32_NetworkAdapterConfiguration instance"
    Wscript.Echo "-----------------------------------"
    Wscript.Echo "Description: " & objItem.Description
    If isNull(objItem.IPAddress) Then
        Wscript.Echo "IPAddress: "
        Wscript.Echo "IPAddress: " & Join(objItem.IPAddress, ",")
    End If
    Wscript.Echo "IPEnabled: " & objItem.IPEnabled
    If isNull(objItem.IPSubnet) Then
        Wscript.Echo "IPSubnet: "
        Wscript.Echo "IPSubnet: " & Join(objItem.IPSubnet, ",")
    End If

Open in new window

All Courses

From novice to tech pro — start learning today.