Jump to content

how to easily get the subnet mask?


 Share

Go to solution Solved by dragan,

Recommended Posts

Welcoming a user to the forum that has > 300 posts :huh:

My UDFs and Tutorials:

Spoiler

UDFs:
Active Directory (NEW 2024-07-28 - Version 1.6.3.0) - Download - General Help & Support - Example Scripts - Wiki
ExcelChart (2017-07-21 - Version 0.4.0.1) - Download - General Help & Support - Example Scripts
OutlookEX (2021-11-16 - Version 1.7.0.0) - Download - General Help & Support - Example Scripts - Wiki
OutlookEX_GUI (2021-04-13 - Version 1.4.0.0) - Download
Outlook Tools (2019-07-22 - Version 0.6.0.0) - Download - General Help & Support - Wiki
PowerPoint (2021-08-31 - Version 1.5.0.0) - Download - General Help & Support - Example Scripts - Wiki
Task Scheduler (2022-07-28 - Version 1.6.0.1) - Download - General Help & Support - Wiki

Standard UDFs:
Excel - Example Scripts - Wiki
Word - Wiki

Tutorials:
ADO - Wiki
WebDriver - Wiki

 

Link to comment
Share on other sites

Welcome to the forum!

I googled it and came up with this article which seems to fit your needs exactly

'?do=embed' frameborder='0' data-embedContent>>

let me know if there is anything else you need

Hi Astormooke

thanks for reply

I had already seen that link, but those scripts return a list of network adapters,

while I would just like the subnet mask of the card with the address @IPaddress1,

something like this: for example,

$IP = @IPAddress1

ConsoleWrite("Subnet mask of @IPAddress1 is " & GiveMeMask($IP) & @CRLF)

Func GiveMeMask($IP)

    $Mask = "...I do not know how"

    Return $Mask
EndFunc   ;==>GiveMeMask

Welcoming a user to the forum that has > 300 posts :huh:

thanks water

. . . .  :D  Never mind, a warm welcome is always a pleasure! :)

 

image.jpeg.9f1a974c98e9f77d824b358729b089b0.jpeg Chimp

small minds discuss people average minds discuss events great minds discuss ideas.... and use AutoIt....

Link to comment
Share on other sites

$theIP1 = @IPAddress1
$subnetIP = _GetSubnetBasedOnIP($theIP1)
if NOT @error then
    MsgBox(0, 'Success', 'For IP: ' & $theIP1 & @CRLF & 'Subnet is: ' & $subnetIP)
Else
    Switch @error
        Case 1
            MsgBox(0, 'Error 1', 'Input IP [' & $theIP1 & '] is not a valid IP address.')
        Case 2
            MsgBox(0, 'Error 2', 'Input IP [' & $theIP1 & '] was not found on this computer.')
        Case 3
            MsgBox(0, 'Error 3', 'WMI is not accessible.')
        Case Else
            MsgBox(0, 'Error X', 'Unknown error occured for the input IP [' & $theIP1 & '].')
    EndSwitch
EndIf

Func _GetSubnetBasedOnIP($theIP)
    if NOT _isIPaddr($theIP) Then Return SetError(1, 0, 0)
    Const $wbemFlagReturnImmediately = 0x10
    Const $wbemFlagForwardOnly = 0x20
    Local $colNICs="", $NIC, $strQuery, $objWMIService, $retVal = ""
    $strQuery = "SELECT * FROM Win32_NetworkAdapterConfiguration"
    $objWMIService = ObjGet("winmgmts:\\.\root\CIMV2")
    If @error then Return SetError(3, 0, 0)
    $colNICs = $objWMIService.ExecQuery($strQuery, "WQL", $wbemFlagReturnImmediately + $wbemFlagForwardOnly)
    If IsObj($colNICs) Then
        For $NIC in $colNICs
            if _isIPaddr($NIC.IPAddress(0)) then
                if $NIC.IPAddress(0) = $theIP Then
                    if _isIPaddr($NIC.IPSubnet(0)) then
                        $retVal = $NIC.IPSubnet(0)
                        ExitLoop
                    EndIf
                EndIf
            EndIf
        Next
    EndIf
    if $retVal = "" Then Return SetError(2, 0, 0)
    Return $retVal
EndFunc

Func _isIPaddr($sIPAddr)
    If NOT StringRegExp($sIPAddr, "^((25[0-5]|2[0-4]\d|[01]?\d?\d)\.){3}(25[0-5]|2[0-4]\d|[01]?\d?\d)$") Then Return SetError(1, 0, False)
    Return True
EndFunc

Link to comment
Share on other sites

Or this way.

Local $vObjWMI = ObjGet("winmgmts:\\" & @ComputerName & "\root\cimv2")
    $vObjItems = $vObjWMI.ExecQuery('SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled=True')
    If IsObj($vObjItems) Then
        For $vObjItem In $vObjItems
            For $i = 0 To UBound($vObjItem.IPAddress) - 1
                If $vObjItem.IPAddress($i) == @IPAddress1 Then
                    ConsoleWrite("Subnet Mask: " & $vObjItem.IPSubnet($i))
                EndIf
            Next
        Next
    EndIf

[font="'courier new', courier, monospace;"]Pastebin UDF | Prowl UDF[/font]

Link to comment
Share on other sites

Thank you both dragan and mrflibblehat for the interesting solutions!

the two are basically the same, but, I did some tests and it has emerged that:

@dragan, your script is well cared for, I like, but it has a small gap, since you are using directly the index 0. ipaddress(0), it happens that if a card has more than one IP address (IP aliasing), and the IP we seek is not the first one, the search may fail.

@
mrflibblehat while your script does not fail even in the presence of IP aliasing because you do the loop on all IP addresses of every single card.

I like them both, thanks


However, since it is possible that some computers do not have WMI access, I would like to obtain the same subnet  using a DLL instead of WMI, as is done >in this post by ProgAndy where a DLL is used but in a way a little bit complicated. I tried to extract only the part that returns the subnet but I gave up.

Do you know how to simplify that script and reduce it as those presented here above?

thanks

edit:

added ProgAndy's post link

Edited by PincoPanco

 

image.jpeg.9f1a974c98e9f77d824b358729b089b0.jpeg Chimp

small minds discuss people average minds discuss events great minds discuss ideas.... and use AutoIt....

Link to comment
Share on other sites

perhaps something like this:
 

$theIP1 = @IPAddress1
$subnetIP = _GetSubnetBasedOnIP($theIP1)
if NOT @error then
    MsgBox(0, 'Success', 'For IP: ' & $theIP1 & @CRLF & 'Subnet is: ' & $subnetIP)
Else
    Switch @error
        Case 1
            MsgBox(0, 'Error 1', 'Input IP [' & $theIP1 & '] is not a valid IP address.')
        Case 2
            MsgBox(0, 'Error 2', 'Input IP [' & $theIP1 & '] was not found on this computer.')
        Case 3
            MsgBox(0, 'Error 3', 'dll open: Iphlpapi.dll, error code: ' & @extended)
        Case 4
            MsgBox(0, 'Error 4', 'dll call function: GetAdaptersInfo, error code: ' & @extended)
        Case 5
            MsgBox(0, 'Error 5', 'dll call function: GetAdaptersInfo with adapter buffer pointer, error code: ' & @extended)
        Case Else
            MsgBox(0, 'Error X', 'Unknown error occured for the input IP [' & $theIP1 & '].')
    EndSwitch
EndIf




;==========================================================================================================================================================
;==========================================================================================================================================================
Func _GetSubnetBasedOnIP($theIP)
    if NOT _isIPaddr($theIP) Then Return SetError(1, 0, 0)

    Local Const $tagIP_ADDRESS_STRING = "char IPAddress[16];"
    Local Const $tagIP_MASK_STRING = "char IPMask[16];"
    Local Const $tagIP_ADDR_STRING = "ptr Next;" & $tagIP_ADDRESS_STRING & $tagIP_MASK_STRING & "DWORD Context;"

    Local Const $tagIP_ADAPTER_INFO = "ptr Next; DWORD ComboIndex; char AdapterName[260];char Description[132]; UINT AddressLength; BYTE Address[8]; dword Index; UINT Type;" & _
            " UINT DhcpEnabled; ptr CurrentIpAddress; ptr IpAddressListNext; char IpAddressListADDRESS[16]; char IpAddressListMASK[16]; DWORD IpAddressListContext; " & _
            "ptr GatewayListNext; char GatewayListADDRESS[16]; char GatewayListMASK[16]; DWORD GatewayListContext; " & _
            "ptr DhcpServerNext; char DhcpServerADDRESS[16]; char DhcpServerMASK[16]; DWORD DhcpServerContext; " & _
            "int HaveWins; " & _
            "ptr PrimaryWinsServerNext; char PrimaryWinsServerADDRESS[16]; char PrimaryWinsServerMASK[16]; DWORD PrimaryWinsServerContext; " & _
            "ptr SecondaryWinsServerNext; char SecondaryWinsServerADDRESS[16]; char SecondaryWinsServerMASK[16]; DWORD SecondaryWinsServerContext; " & _
            "DWORD LeaseObtained; DWORD LeaseExpires;"

    Local $dll = DllOpen("Iphlpapi.dll")
    If @error then Return SetError(3, @error, 0)
    Local $ret = DllCall($dll, "dword", "GetAdaptersInfo", "ptr", 0, "dword*", 0)
    If @error then
        DllClose($dll)
        Return SetError(4, @error, 0)
    EndIf

    Local $adapterBuffer = DllStructCreate("byte[" & $ret[2] & "]")
    Local $adapterBuffer_pointer = DllStructGetPtr($adapterBuffer)
    DllCall($dll, "dword", "GetAdaptersInfo", "ptr", $adapterBuffer_pointer, "dword*", $ret[2])
    If @error then
        $adapterBuffer = ""
        $adapterBuffer_pointer = ""
        DllClose($dll)
        Return SetError(5, @error, 0)
    EndIf
    Local $adapter = DllStructCreate($tagIP_ADAPTER_INFO, $adapterBuffer_pointer)

    Local $retVal = ""
    Local $allArray = _GetAllIps(DllStructGetPtr($adapter, "IpAddressListNext"), $tagIP_ADDR_STRING)
    if IsArray($allArray) Then
        For $i = 0 to UBound($allArray)-1
            if _isIPaddr($allArray[$i][0]) then
                if $allArray[$i][0] = $theIP Then
                    if _isIPaddr($allArray[$i][1]) then
                        $retVal = $allArray[$i][1]
                        ExitLoop
                    EndIf
                EndIf
            EndIf
        Next
    EndIf

    $adapterBuffer = ""
    $adapterBuffer_pointer = ""
    DllClose($dll)
    if $retVal = "" Then Return SetError(2, 0, 0)
    Return $retVal
EndFunc

Func _GetAllIps($Ptr, $tagIP_ADDR_STRING)
    Local $IPStruct, $Index = 0
    Local $IPArray[1][3]
    Do
        ReDim $IPArray[$Index+1][3]
        $IPStruct = DllStructCreate($tagIP_ADDR_STRING,$ptr)
        $IPArray[$Index][0] = DllStructGetData($IPStruct,"IPAddress")
        $IPArray[$Index][1] = DllStructGetData($IPStruct,"IPMask")
        $IPArray[$Index][2] = DllStructGetData($IPStruct,"Context")
        $Ptr = DllStructGetData($IPStruct,"Next")
        $Index += 1
    Until $Ptr = 0
    Return $IPArray
EndFunc

Func _isIPaddr($sIPAddr)
    If NOT StringRegExp($sIPAddr, "^((25[0-5]|2[0-4]\d|[01]?\d?\d)\.){3}(25[0-5]|2[0-4]\d|[01]?\d?\d)$") Then Return SetError(1, 0, False)
    Return True
EndFunc
Edited by dragan
Link to comment
Share on other sites

Hi dragan, thanks for the script,

I tried it but I always get
Error 2 Input Address [xx.xx.xx.xx] was not found on this computer. :huh2:

 

image.jpeg.9f1a974c98e9f77d824b358729b089b0.jpeg Chimp

small minds discuss people average minds discuss events great minds discuss ideas.... and use AutoIt....

Link to comment
Share on other sites

And when you run >this script, do you find your @IPAddress1 in the console XML output?

@IPAddress1 is the IP of the first addapter, maybe that's not the address you're looking for?

yes, that script returns right values (in XML format)

also >this other script (a similar one) returns right values in plain format

Edited by PincoPanco

 

image.jpeg.9f1a974c98e9f77d824b358729b089b0.jpeg Chimp

small minds discuss people average minds discuss events great minds discuss ideas.... and use AutoIt....

Link to comment
Share on other sites

ConsoleWrite(_GetBroadcastAddress(@IPAddress1, '255.255.255.0') & @CRLF)

; Based on the idea by: CodyBarrett - http://www.autoitscript.com/forum/topic/122072-serverless-udp/
Func _GetBroadcastAddress($sIPAddress, $sSubnetMask)
    Local $aIPAddress = StringSplit($sIPAddress, '.'), $aSubnetMask = StringSplit($sSubnetMask, '.')
    $sIPAddress = ''
    For $i = 1 To $aIPAddress[0]
        $aIPAddress[$i] = BitAND($aIPAddress[$i], $aSubnetMask[$i])
        If $aSubnetMask[$i] = 0 Then
            $aIPAddress[$i] = '255'
        EndIf
        $sIPAddress &= $aIPAddress[$i] & '.'
    Next
    Return StringTrimRight($sIPAddress, 1)
EndFunc   ;==>_GetBroadcaseAddress

I use this...

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

try this script, and see if your IP is among the array:

 

#include <Array.au3>

$theIP1 = @IPAddress1
$subnetIP = _GetSubnetBasedOnIP($theIP1)
if NOT @error then
    MsgBox(0, 'Success', 'For IP: ' & $theIP1 & @CRLF & 'Subnet is: ' & $subnetIP)
Else
    Switch @error
        Case 1
            MsgBox(0, 'Error 1', 'Input IP [' & $theIP1 & '] is not a valid IP address.')
        Case 2
            MsgBox(0, 'Error 2', 'Input IP [' & $theIP1 & '] was not found on this computer.')
        Case 3
            MsgBox(0, 'Error 3', 'dll open: Iphlpapi.dll, error code: ' & @extended)
        Case 4
            MsgBox(0, 'Error 4', 'dll call function: GetAdaptersInfo, error code: ' & @extended)
        Case 5
            MsgBox(0, 'Error 5', 'dll call function: GetAdaptersInfo with adapter buffer pointer, error code: ' & @extended)
        Case Else
            MsgBox(0, 'Error X', 'Unknown error occured for the input IP [' & $theIP1 & '].')
    EndSwitch
EndIf




;==========================================================================================================================================================
;==========================================================================================================================================================
Func _GetSubnetBasedOnIP($theIP)
    if NOT _isIPaddr($theIP) Then Return SetError(1, 0, 0)

    Local Const $tagIP_ADDRESS_STRING = "char IPAddress[16];"
    Local Const $tagIP_MASK_STRING = "char IPMask[16];"
    Local Const $tagIP_ADDR_STRING = "ptr Next;" & $tagIP_ADDRESS_STRING & $tagIP_MASK_STRING & "DWORD Context;"

    Local Const $tagIP_ADAPTER_INFO = "ptr Next; DWORD ComboIndex; char AdapterName[260];char Description[132]; UINT AddressLength; BYTE Address[8]; dword Index; UINT Type;" & _
            " UINT DhcpEnabled; ptr CurrentIpAddress; ptr IpAddressListNext; char IpAddressListADDRESS[16]; char IpAddressListMASK[16]; DWORD IpAddressListContext; " & _
            "ptr GatewayListNext; char GatewayListADDRESS[16]; char GatewayListMASK[16]; DWORD GatewayListContext; " & _
            "ptr DhcpServerNext; char DhcpServerADDRESS[16]; char DhcpServerMASK[16]; DWORD DhcpServerContext; " & _
            "int HaveWins; " & _
            "ptr PrimaryWinsServerNext; char PrimaryWinsServerADDRESS[16]; char PrimaryWinsServerMASK[16]; DWORD PrimaryWinsServerContext; " & _
            "ptr SecondaryWinsServerNext; char SecondaryWinsServerADDRESS[16]; char SecondaryWinsServerMASK[16]; DWORD SecondaryWinsServerContext; " & _
            "DWORD LeaseObtained; DWORD LeaseExpires;"

    Local $dll = DllOpen("Iphlpapi.dll")
    If @error then Return SetError(3, @error, 0)
    Local $ret = DllCall($dll, "dword", "GetAdaptersInfo", "ptr", 0, "dword*", 0)
    If @error then
        DllClose($dll)
        Return SetError(4, @error, 0)
    EndIf

    Local $adapterBuffer = DllStructCreate("byte[" & $ret[2] & "]")
    Local $adapterBuffer_pointer = DllStructGetPtr($adapterBuffer)
    DllCall($dll, "dword", "GetAdaptersInfo", "ptr", $adapterBuffer_pointer, "dword*", $ret[2])
    If @error then
        $adapterBuffer = ""
        $adapterBuffer_pointer = ""
        DllClose($dll)
        Return SetError(5, @error, 0)
    EndIf
    Local $adapter = DllStructCreate($tagIP_ADAPTER_INFO, $adapterBuffer_pointer)

    Local $retVal = ""
    Local $TEMPVAL[1][2]
    Local $allArray = _GetAllIps(DllStructGetPtr($adapter, "IpAddressListNext"), $tagIP_ADDR_STRING)
    if IsArray($allArray) Then
        $TEMPVAL[0][0] = UBound($allArray)
        For $i = 0 to UBound($allArray)-1
            ReDim $TEMPVAL[UBound($TEMPVAL)+1][2]
            $TEMPVAL[UBound($TEMPVAL)-1][0] = $allArray[$i][0]
            $TEMPVAL[UBound($TEMPVAL)-1][1] = $allArray[$i][1]
            if _isIPaddr($allArray[$i][0]) then
                if $allArray[$i][0] = $theIP Then
                    if _isIPaddr($allArray[$i][1]) then
                        $retVal = $allArray[$i][1]
;~                      ExitLoop
                    EndIf
                EndIf
            EndIf
        Next
    EndIf
    _ArrayDisplay($TEMPVAL)
    $adapterBuffer = ""
    $adapterBuffer_pointer = ""
    DllClose($dll)
    if $retVal = "" Then Return SetError(2, 0, 0)
    Return $retVal
EndFunc

Func _GetAllIps($Ptr, $tagIP_ADDR_STRING)
    Local $IPStruct, $Index = 0
    Local $IPArray[1][3]
    Do
        ReDim $IPArray[$Index+1][3]
        $IPStruct = DllStructCreate($tagIP_ADDR_STRING,$ptr)
        $IPArray[$Index][0] = DllStructGetData($IPStruct,"IPAddress")
        $IPArray[$Index][1] = DllStructGetData($IPStruct,"IPMask")
        $IPArray[$Index][2] = DllStructGetData($IPStruct,"Context")
        $Ptr = DllStructGetData($IPStruct,"Next")
        $Index += 1
    Until $Ptr = 0
    Return $IPArray
EndFunc

Func _isIPaddr($sIPAddr)
    If NOT StringRegExp($sIPAddr, "^((25[0-5]|2[0-4]\d|[01]?\d?\d)\.){3}(25[0-5]|2[0-4]\d|[01]?\d?\d)$") Then Return SetError(1, 0, False)
    Return True
EndFunc

EDIT :
I just figured out, you probably have the same gateway IP as your @IPAddress1, so this will probably give you the subnet:
 

$theIP1 = @IPAddress1
$subnetIP = _GetSubnetBasedOnIP($theIP1)
if NOT @error then
    Local $type = ''
    Switch @extended
        Case 0
            $type = 'Regular adapter IP'
        Case 1
            $type = 'Gateway IP'
        Case Else
            $type = 'Unknown IP'
    EndSwitch
    MsgBox(0, 'Success', 'For IP:' & @TAB & $theIP1 & @CRLF & 'Subnet is:' & @TAB & $subnetIP & @CRLF & 'IP Type:' & @TAB & $type)
Else
    Switch @error
        Case 1
            MsgBox(0, 'Error 1', 'Input IP [' & $theIP1 & '] is not a valid IP address.')
        Case 2
            MsgBox(0, 'Error 2', 'Input IP [' & $theIP1 & '] was not found on this computer.')
        Case 3
            MsgBox(0, 'Error 3', 'dll open: Iphlpapi.dll, error code: ' & @extended)
        Case 4
            MsgBox(0, 'Error 4', 'dll call function: GetAdaptersInfo, error code: ' & @extended)
        Case 5
            MsgBox(0, 'Error 5', 'dll call function: GetAdaptersInfo with adapter buffer pointer, error code: ' & @extended)
        Case Else
            MsgBox(0, 'Error X', 'Unknown error occured for the input IP [' & $theIP1 & '].')
    EndSwitch
EndIf


;==========================================================================================================================================================
;==========================================================================================================================================================
Func _GetSubnetBasedOnIP($theIP)
    if NOT _isIPaddr($theIP) Then Return SetError(1, 0, 0)

    Local Const $tagIP_ADDRESS_STRING = "char IPAddress[16];"
    Local Const $tagIP_MASK_STRING = "char IPMask[16];"
    Local Const $tagIP_ADDR_STRING = "ptr Next;" & $tagIP_ADDRESS_STRING & $tagIP_MASK_STRING & "DWORD Context;"

    Local Const $tagIP_ADAPTER_INFO = "ptr Next; DWORD ComboIndex; char AdapterName[260];char Description[132]; UINT AddressLength; BYTE Address[8]; dword Index; UINT Type;" & _
            " UINT DhcpEnabled; ptr CurrentIpAddress; ptr IpAddressListNext; char IpAddressListADDRESS[16]; char IpAddressListMASK[16]; DWORD IpAddressListContext; " & _
            "ptr GatewayListNext; char GatewayListADDRESS[16]; char GatewayListMASK[16]; DWORD GatewayListContext; " & _
            "ptr DhcpServerNext; char DhcpServerADDRESS[16]; char DhcpServerMASK[16]; DWORD DhcpServerContext; " & _
            "int HaveWins; " & _
            "ptr PrimaryWinsServerNext; char PrimaryWinsServerADDRESS[16]; char PrimaryWinsServerMASK[16]; DWORD PrimaryWinsServerContext; " & _
            "ptr SecondaryWinsServerNext; char SecondaryWinsServerADDRESS[16]; char SecondaryWinsServerMASK[16]; DWORD SecondaryWinsServerContext; " & _
            "DWORD LeaseObtained; DWORD LeaseExpires;"

    Local $dll = DllOpen("Iphlpapi.dll")
    If @error then Return SetError(3, @error, 0)
    Local $ret = DllCall($dll, "dword", "GetAdaptersInfo", "ptr", 0, "dword*", 0)
    If @error then
        DllClose($dll)
        Return SetError(4, @error, 0)
    EndIf

    Local $adapterBuffer = DllStructCreate("byte[" & $ret[2] & "]")
    Local $adapterBuffer_pointer = DllStructGetPtr($adapterBuffer)
    DllCall($dll, "dword", "GetAdaptersInfo", "ptr", $adapterBuffer_pointer, "dword*", $ret[2])
    If @error then
        $adapterBuffer = ""
        $adapterBuffer_pointer = ""
        DllClose($dll)
        Return SetError(5, @error, 0)
    EndIf
    Local $adapter = DllStructCreate($tagIP_ADAPTER_INFO, $adapterBuffer_pointer)
    Local $IPType = -1
    Local $FoundIt = False

    Local $retVal = ""
    Local $allArray = _GetAllIps(DllStructGetPtr($adapter, "IpAddressListNext"), $tagIP_ADDR_STRING)
    if IsArray($allArray) Then
        For $i = 0 to UBound($allArray)-1
            if NOT _isIPaddr($allArray[$i][0]) then ContinueLoop
            if $allArray[$i][0] <> $theIP Then ContinueLoop
            if NOT _isIPaddr($allArray[$i][1]) then ContinueLoop
            $retVal = $allArray[$i][1]
            $IPType = 0
            $FoundIt = True
            ExitLoop
        Next
    EndIf

    if NOT $FoundIt Then
        $allArray = _GetAllIps(DllStructGetPtr($adapter, "GatewayListNext"), $tagIP_ADDR_STRING)
        if IsArray($allArray) Then
            For $i = 0 to UBound($allArray)-1
                if NOT _isIPaddr($allArray[$i][0]) then ContinueLoop
                if $allArray[$i][0] <> $theIP Then ContinueLoop
                if NOT _isIPaddr($allArray[$i][1]) then ContinueLoop
                $retVal = $allArray[$i][1]
                $IPType = 1
                $FoundIt = True
                ExitLoop
            Next
        EndIf
    EndIf

    $adapterBuffer = ""
    $adapterBuffer_pointer = ""
    DllClose($dll)

    if NOT $FoundIt Then Return SetError(2, 0, 0)
    Return SetError(0, $IPType, $retVal)
EndFunc

Func _GetAllIps($Ptr, $tagIP_ADDR_STRING)
    Local $IPStruct, $Index = 0
    Local $IPArray[1][3]
    Do
        ReDim $IPArray[$Index+1][3]
        $IPStruct = DllStructCreate($tagIP_ADDR_STRING,$ptr)
        $IPArray[$Index][0] = DllStructGetData($IPStruct,"IPAddress")
        $IPArray[$Index][1] = DllStructGetData($IPStruct,"IPMask")
        $IPArray[$Index][2] = DllStructGetData($IPStruct,"Context")
        $Ptr = DllStructGetData($IPStruct,"Next")
        $Index += 1
    Until $Ptr = 0
    Return $IPArray
EndFunc

Func _isIPaddr($sIPAddr)
    If NOT StringRegExp($sIPAddr, "^((25[0-5]|2[0-4]\d|[01]?\d?\d)\.){3}(25[0-5]|2[0-4]\d|[01]?\d?\d)$") Then Return SetError(1, 0, False)
    Return True
EndFunc

if this doesn't give you the results also, tell me which type does? DHCPSERVER? PRIMARYWINSSERVER? SECONDARYWINSSERVER?

Edited by dragan
Link to comment
Share on other sites

$IP = @IPAddress1
$PID = Run("ipconfig", "", @SW_HIDE, 2)
While ProcessExists($PID)
    Sleep(10)
WEnd
$Text = StdoutRead($PID)
$aText = StringSplit($Text, @CRLF, 1)
For $I = 1 to $aText[0]
    If StringInStr($aText[$I], $IP) Then
        $Subnet = StringMid($aText[$I + 1], StringInStr($aText[$I + 1], ":") + 2)
        ExitLoop
    EndIf
Next
ConsoleWrite("Subnet Mask = " & $Subnet & @CRLF)

If I posted any code, assume that code was written using the latest release version unless stated otherwise. Also, if it doesn't work on XP I can't help with that because I don't have access to XP, and I'm not going to.
Give a programmer the correct code and he can do his work for a day. Teach a programmer to debug and he can do his work for a lifetime - by Chirag Gude
How to ask questions the smart way!

I hereby grant any person the right to use any code I post, that I am the original author of, on the autoitscript.com forums, unless I've specifically stated otherwise in the code or the thread post. If you do use my code all I ask, as a courtesy, is to make note of where you got it from.

Back up and restore Windows user files _Array.au3 - Modified array functions that include support for 2D arrays.  -  ColorChooser - An add-on for SciTE that pops up a color dialog so you can select and paste a color code into a script.  -  Customizable Splashscreen GUI w/Progress Bar - Create a custom "splash screen" GUI with a progress bar and custom label.  -  _FileGetProperty - Retrieve the properties of a file  -  SciTE Toolbar - A toolbar demo for use with the SciTE editor  -  GUIRegisterMsg demo - Demo script to show how to use the Windows messages to interact with controls and your GUI.  -   Latin Square password generator

Link to comment
Share on other sites

ConsoleWrite(_GetBroadcastAddress(@IPAddress1, '255.255.255.0') & @CRLF)

; Based on the idea by: CodyBarrett - http://www.autoitscript.com/forum/topic/122072-serverless-udp/
Func _GetBroadcastAddress($sIPAddress, $sSubnetMask)
    Local $aIPAddress = StringSplit($sIPAddress, '.'), $aSubnetMask = StringSplit($sSubnetMask, '.')
    $sIPAddress = ''
    For $i = 1 To $aIPAddress[0]
        $aIPAddress[$i] = BitAND($aIPAddress[$i], $aSubnetMask[$i])
        If $aSubnetMask[$i] = 0 Then
            $aIPAddress[$i] = '255'
        EndIf
        $sIPAddress &= $aIPAddress[$i] & '.'
    Next
    Return StringTrimRight($sIPAddress, 1)
EndFunc   ;==>_GetBroadcaseAddress

I use this...

 

Thanks guinness, ... I am in search of the subnet mask not the broadcast address,

thanks a lot anyway! , this will also be useful to me :)

 

image.jpeg.9f1a974c98e9f77d824b358729b089b0.jpeg Chimp

small minds discuss people average minds discuss events great minds discuss ideas.... and use AutoIt....

Link to comment
Share on other sites

$IP = @IPAddress1
$PID = Run("ipconfig", "", @SW_HIDE, 2)
While ProcessExists($PID)
    Sleep(10)
WEnd
$Text = StdoutRead($PID)
$aText = StringSplit($Text, @CRLF, 1)
For $I = 1 to $aText[0]
    If StringInStr($aText[$I], $IP) Then
        $Subnet = StringMid($aText[$I + 1], StringInStr($aText[$I + 1], ":") + 2)
        ExitLoop
    EndIf
Next
ConsoleWrite("Subnet Mask = " & $Subnet & @CRLF)

 

hey this works, .... a little bit "screen text based" but it works,

also I have to hope that the subnet is always the next of IP on screen output.

I like this "original method" (looks a bit like a copy / paste) :)

but maybe a dll based script will point exactly to the "mask" field...

Thanks BrewManNH

 

image.jpeg.9f1a974c98e9f77d824b358729b089b0.jpeg Chimp

small minds discuss people average minds discuss events great minds discuss ideas.... and use AutoIt....

Link to comment
Share on other sites

The subnet mask is ALWAYS the line after the IP address in IPCONFIG, at least it always has been since Windows 98 as far as I can recall. If it changes, you can always do the search based on the @OSVersion. But this is by far the easiest and quickest way to get the Subnet mask information. As long as the IP address is correct, the subnet mask information will be too, mainly because only one NIC can have that IP address regardless of how many NICs you have in the computer.

If I posted any code, assume that code was written using the latest release version unless stated otherwise. Also, if it doesn't work on XP I can't help with that because I don't have access to XP, and I'm not going to.
Give a programmer the correct code and he can do his work for a day. Teach a programmer to debug and he can do his work for a lifetime - by Chirag Gude
How to ask questions the smart way!

I hereby grant any person the right to use any code I post, that I am the original author of, on the autoitscript.com forums, unless I've specifically stated otherwise in the code or the thread post. If you do use my code all I ask, as a courtesy, is to make note of where you got it from.

Back up and restore Windows user files _Array.au3 - Modified array functions that include support for 2D arrays.  -  ColorChooser - An add-on for SciTE that pops up a color dialog so you can select and paste a color code into a script.  -  Customizable Splashscreen GUI w/Progress Bar - Create a custom "splash screen" GUI with a progress bar and custom label.  -  _FileGetProperty - Retrieve the properties of a file  -  SciTE Toolbar - A toolbar demo for use with the SciTE editor  -  GUIRegisterMsg demo - Demo script to show how to use the Windows messages to interact with controls and your GUI.  -   Latin Square password generator

Link to comment
Share on other sites

  • Solution

if you're still interested, this is the way via Iphlpapi.dll:
 

$theIP1 = @IPAddress1
$subnetIP = _GetSubnetBasedOnIP($theIP1)
if NOT @error then
    Local $type = ''
    Switch @extended
        Case 0
            $type = 'Regular adapter IP'
        Case 1
            $type = 'Gateway IP'
        Case 2
            $type = 'DHCP Server IP'
        Case 3
            $type = 'PrimaryWinsServer IP'
        Case 4
            $type = 'SecondaryWinsServer IP'
        Case Else
            $type = 'Unknown IP'
    EndSwitch
    MsgBox(0, 'Success', 'For IP:' & @TAB & $theIP1 & @CRLF & 'Subnet is:' & @TAB & $subnetIP & @CRLF & 'IP Type:' & @TAB & $type)
Else
    Switch @error
        Case 1
            MsgBox(0, 'Error 1', 'Input IP [' & $theIP1 & '] is not a valid IP address.')
        Case 2
            MsgBox(0, 'Error 2', 'Input IP [' & $theIP1 & '] was not found on this computer.')
        Case 3
            MsgBox(0, 'Error 3', 'dll open: Iphlpapi.dll, error code: ' & @extended)
        Case 4
            MsgBox(0, 'Error 4', 'dll call function: GetAdaptersInfo, error code: ' & @extended)
        Case 5
            MsgBox(0, 'Error 5', 'dll call function: GetAdaptersInfo with adapter buffer pointer, error code: ' & @extended)
        Case Else
            MsgBox(0, 'Error X', 'Unknown error occured for the input IP [' & $theIP1 & '].')
    EndSwitch
EndIf


;==========================================================================================================================================================
;==========================================================================================================================================================
Func _GetSubnetBasedOnIP($theIP)
    if NOT _isIPaddr($theIP) Then Return SetError(1, 0, 0)

    Local Const $tagIP_ADDRESS_STRING = "char IPAddress[16];"
    Local Const $tagIP_MASK_STRING = "char IPMask[16];"
    Local Const $tagIP_ADDR_STRING = "ptr Next;" & $tagIP_ADDRESS_STRING & $tagIP_MASK_STRING & "DWORD Context;"

    Local Const $tagIP_ADAPTER_INFO = "ptr Next; DWORD ComboIndex; char AdapterName[260];char Description[132]; UINT AddressLength; BYTE Address[8]; dword Index; UINT Type;" & _
            " UINT DhcpEnabled; ptr CurrentIpAddress; ptr IpAddressListNext; char IpAddressListADDRESS[16]; char IpAddressListMASK[16]; DWORD IpAddressListContext; " & _
            "ptr GatewayListNext; char GatewayListADDRESS[16]; char GatewayListMASK[16]; DWORD GatewayListContext; " & _
            "ptr DhcpServerNext; char DhcpServerADDRESS[16]; char DhcpServerMASK[16]; DWORD DhcpServerContext; " & _
            "int HaveWins; " & _
            "ptr PrimaryWinsServerNext; char PrimaryWinsServerADDRESS[16]; char PrimaryWinsServerMASK[16]; DWORD PrimaryWinsServerContext; " & _
            "ptr SecondaryWinsServerNext; char SecondaryWinsServerADDRESS[16]; char SecondaryWinsServerMASK[16]; DWORD SecondaryWinsServerContext; " & _
            "DWORD LeaseObtained; DWORD LeaseExpires;"

    Local $dll = DllOpen("Iphlpapi.dll")
    If @error then Return SetError(3, @error, 0)
    Local $ret = DllCall($dll, "dword", "GetAdaptersInfo", "ptr", 0, "dword*", 0)
    If @error then
        DllClose($dll)
        Return SetError(4, @error, 0)
    EndIf

    Local $adapterBuffer = DllStructCreate("byte[" & $ret[2] & "]")
    Local $adapterBuffer_pointer = DllStructGetPtr($adapterBuffer)
    DllCall($dll, "dword", "GetAdaptersInfo", "ptr", $adapterBuffer_pointer, "dword*", $ret[2])
    If @error then
        $adapterBuffer = ""
        $adapterBuffer_pointer = ""
        DllClose($dll)
        Return SetError(5, @error, 0)
    EndIf
    Local $adapter = DllStructCreate($tagIP_ADAPTER_INFO, $adapterBuffer_pointer)
    Local $IPType = -1
    Local $FoundIt = False

    Local $retVal = ""
    Do
        Local $allArray = _GetAllIps(DllStructGetPtr($adapter, "IpAddressListNext"), $tagIP_ADDR_STRING)
        if IsArray($allArray) Then
            For $i = 0 to UBound($allArray)-1
                if NOT _isIPaddr($allArray[$i][0]) then ContinueLoop
                if $allArray[$i][0] <> $theIP Then ContinueLoop
                if NOT _isIPaddr($allArray[$i][1]) then ContinueLoop
                $retVal = $allArray[$i][1]
                $IPType = 0
                $FoundIt = True
                ExitLoop
            Next
        EndIf

        if NOT $FoundIt Then
            $allArray = _GetAllIps(DllStructGetPtr($adapter, "GatewayListNext"), $tagIP_ADDR_STRING)
            if IsArray($allArray) Then
                For $i = 0 to UBound($allArray)-1
                    if NOT _isIPaddr($allArray[$i][0]) then ContinueLoop
                    if $allArray[$i][0] <> $theIP Then ContinueLoop
                    if NOT _isIPaddr($allArray[$i][1]) then ContinueLoop
                    $retVal = $allArray[$i][1]
                    $IPType = 1
                    $FoundIt = True
                    ExitLoop
                Next
            EndIf
        EndIf

        if NOT $FoundIt Then
            Local $ptr1 = DllStructGetPtr($adapter, "DhcpServerNext")
            Local $IPStruct = DllStructCreate($tagIP_ADDR_STRING,$ptr1)
            Local $curIP = DllStructGetData($IPStruct,"IPAddress")
            Local $curSubnet = DllStructGetData($IPStruct,"IPMask")
            if _isIPaddr($curIP) AND _isIPaddr($curSubnet) Then
                if $curIP = $theIP then
                    $retVal = $curSubnet
                    $IPType = 2
                    $FoundIt = True
                EndIf
            EndIf
        EndIf

        if NOT $FoundIt Then
            Local $ptr1 = DllStructGetPtr($adapter, "PrimaryWinsServerNext")
            Local $IPStruct = DllStructCreate($tagIP_ADDR_STRING,$ptr1)
            Local $curIP = DllStructGetData($IPStruct,"IPAddress")
            Local $curSubnet = DllStructGetData($IPStruct,"IPMask")
            if _isIPaddr($curIP) AND _isIPaddr($curSubnet) Then
                if $curIP = $theIP then
                    $retVal = $curSubnet
                    $IPType = 3
                    $FoundIt = True
                EndIf
            EndIf
        EndIf

        if NOT $FoundIt Then
            Local $ptr1 = DllStructGetPtr($adapter, "SecondaryWinsServerNext")
            Local $IPStruct = DllStructCreate($tagIP_ADDR_STRING,$ptr1)
            Local $curIP = DllStructGetData($IPStruct,"IPAddress")
            Local $curSubnet = DllStructGetData($IPStruct,"IPMask")
            if _isIPaddr($curIP) AND _isIPaddr($curSubnet) Then
                if $curIP = $theIP then
                    $retVal = $curSubnet
                    $IPType = 4
                    $FoundIt = True
                EndIf
            EndIf
        EndIf

        if $FoundIt Then ExitLoop

        $ptr = DllStructGetData($adapter, "Next")
        $adapter = DllStructCreate($tagIP_ADAPTER_INFO, $ptr)
    Until @error

    $adapterBuffer = ""
    $adapterBuffer_pointer = ""
    DllClose($dll)

    if NOT $FoundIt Then Return SetError(2, 0, 0)
    Return SetError(0, $IPType, $retVal)
EndFunc

Func _GetAllIps($Ptr, $tagIP_ADDR_STRING)
    Local $IPStruct, $Index = 0
    Local $IPArray[1][3]
    Do
        ReDim $IPArray[$Index+1][3]
        $IPStruct = DllStructCreate($tagIP_ADDR_STRING,$ptr)
        $IPArray[$Index][0] = DllStructGetData($IPStruct,"IPAddress")
        $IPArray[$Index][1] = DllStructGetData($IPStruct,"IPMask")
        $IPArray[$Index][2] = DllStructGetData($IPStruct,"Context")
        $Ptr = DllStructGetData($IPStruct,"Next")
        $Index += 1
    Until $Ptr = 0
    Return $IPArray
EndFunc

Func _isIPaddr($sIPAddr)
    If NOT StringRegExp($sIPAddr, "^((25[0-5]|2[0-4]\d|[01]?\d?\d)\.){3}(25[0-5]|2[0-4]\d|[01]?\d?\d)$") Then Return SetError(1, 0, False)
    Return True
EndFunc
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...