Search code examples
powershellbinaryipv4subnet

Subnet and IP address ANDing trailing 0's


So I have a script that is ANDing an IPv4 address and a subnet address. Not checking to see if it is a valid input (which I should add), it converts the input to binary.

if ($readInput -match "y"){
    $readIP = read-host "Please input an IPv4 address to be ANDed " 

    # need to add subnet mask later. 
    $readSub = read-host "Please input the Subnet Mask "


    #need to delimite '.'
    #$readIP.split "."
    #$readSub.split "."

    #need to join them

    #convert IPv4 address to binary, period seperated at each octet. (input ip, base 2)
    $binIP = [convert]::ToString($readIP,2)
    write-host "$binIP" -backgroundcolor "white" -foregroundcolor "black"
    ## need to have two 32 element array that compares each 1 and 0. loop through each one with a counter and compare them with
    ## conditional if statements

    #conditional statements for /cider notion to equal a binary number (mask, base 2)
    $binSub = [convert]::ToString($readSub,2)
    write-host "$binSub" -backgroundcolor "white" -foregroundcolor "black"
}

The input is:

19216823
2552552550

The output is:

1001001010011100110110111
10011000001001001101110001100110

Do I have to add 7 trailing 0's at the end of the IP address in order to perform proper ANDing?


Solution

  • It's usually easier to use the [IPAddress] class. Example:

    $ip = [IPAddress] "192.168.32.76"
    $networkMask = [IPAddress] "255.255.255.0"
    $networkID = [IPAddress] ($ip.Address -band $networkMask.Address)
    $networkID.IPAddressToString  # outputs "192.168.32.0"
    

    If you want to count the bits in a network mask string, you can use a function like this:

    function ConvertTo-IPv4MaskBits {
      param(
        [parameter(Mandatory=$true)]
        [String] $MaskString
      )
      $mask = ([IPAddress] $MaskString).Address
      for ( $bitCount = 0; $mask -ne 0; $bitCount++ ) {
        $mask = $mask -band ($mask - 1)
      }
      $bitCount
    }
    

    This function assumes a correctly formed network mask ID.

    A full write-up and some more functions are available in an article I wrote a while back:

    IT Pro Today - Working with IPv4 Addresses in PowerShell