🡠 Back to all articles

Converting a string with an IPv4 address to an integer with PowerShell

Contents

  1. Function description
  2. The function itself
  3. Validating function input
  4. Step-by-step walkthrough
  5. Using the function: checking whether the IPv4 address belongs to the network

Function description

The function Convert-StringIPToIntIP converts a string with an IP address to its integer representation. For example, the function will convert value “192.168.10.2” of type String to 1100 0000 1010 1000 0000 1010 0000 0010 of type Int32.

Function parameter:

Return value:

Usage example:

PS C:\> $IPAddress = Convert-StringIPToIntIP "192.168.10.2" PS C:\> PS C:\> $IPAddress -1062729214 PS C:\> PS C:\> [Convert]::ToString($IPAddress, 2) 11000000101010000000101000000010

The function itself

...is very straight forward:

function Convert-StringIPToIntIP { param ( [Parameter(Mandatory)] [ValidatePattern( "^(0|[1-9]\d?|1\d\d|2[0-4]\d|25[0-5])(\.(0|[1-9]\d?|1\d\d|2[0-4]\d|25[0-5])){3}$" )] [string] $IPAddressString ) $IPAddressString.Split(".") | foreach { $IPAddress = 0; $IPAddressByte = 0 } { [int]::TryParse($_, [ref] $IPAddressByte) | Out-Null $IPAddress = $IPAddress -shl 8 -bor $IPAddressByte } return $IPAddress }

The input is validated with the ValidatePattern attribute to ensure that the string passed to the function contains an IP address: four numbers in range 0–255 separated by a dot symbol.

The foreach comdlet initializes variables that will be used at each iteration:

Then foreach processes each byte of the IP address:

After all the iterations have been completed, $IPAddress contains all the bytes from the input string.

Validating function input

To make sure that the string passed to the function contains a valid IP address, the ValidatePattern attribute is used, that allows to specify a regular expression that parameter values should match. If you are not familiar with regular expressions, here is an illustration that will help you to sort things out:

Step-by-step walkthrough

Here is the example of how the conversion is done for the "192.168.10.2" address:

  1. Create Int32 variables that will contain the result and the current byte of the IP address:
    $IPAddress = 0; $IPAddressByte = 0
  2. Split the string "192.168.10.2" into array of four strings: { "192", "168", "10", "2" }.
    $IPAddressString.Split(".")
  3. For each string in the array:
    • Convert each string from the array to Int32:
      [int]::TryParse($_, [ref] $IPAddressByte) | Out-Null
    • Shift the result ($IPAddress) left by 8 bits and add $IPAddressByte to it:
      $IPAddress = $IPAddress -shl 8 -bor $IPAddressByte
    Iteration 1 (for the string "192"):
    • Convert IP address byte from String to Int32:
      [String] 192 = [Int32] 0000 0000 0000 0000 0000 0000 1100 0000
    • Shift the resulting Int32 variable left by 8 bits:
      0000 0000 0000 0000 0000 0000 0000 0000 << 8 --------------------------------------------- 0000 0000 0000 0000 0000 0000 0000 0000
    • Add IP address byte to the result:
      0000 0000 0000 0000 0000 0000 0000 0000 OR 0000 0000 0000 0000 0000 0000 1100 0000 --------------------------------------------- 0000 0000 0000 0000 0000 0000 1100 0000
    Iteration 2 (for the string "168"):
    • Convert IP address byte from String to Int32:
      [String] 168 = [Int32] 0000 0000 0000 0000 0000 0000 1010 1000
    • Shift the resulting Int32 variable left by 8 bits:
      0000 0000 0000 0000 0000 0000 1100 0000 << 8 --------------------------------------------- 0000 0000 0000 0000 1100 0000 0000 0000
    • Add IP address byte to the result:
      0000 0000 0000 0000 1100 0000 0000 0000 OR 0000 0000 0000 0000 0000 0000 1010 1000 --------------------------------------------- 0000 0000 0000 0000 1100 0000 1010 1000
    Iteration 3 (for the string "10"):
    • Convert IP address byte from String to Int32:
      [String] 10 = [Int32] 0000 0000 0000 0000 0000 0000 0000 1010
    • Shift the resulting Int32 variable left by 8 bits:
      0000 0000 0000 0000 1100 0000 1010 1000 << 8 --------------------------------------------- 0000 0000 1100 0000 1010 1000 0000 0000
    • Add IP address byte to the result:
      0000 0000 1100 0000 1010 1000 0000 0000 OR 0000 0000 0000 0000 0000 0000 0000 1010 --------------------------------------------- 0000 0000 1100 0000 1010 1000 0000 1010
    Iteration 4 (for the string "2"):
    • Convert IP address byte from String to Int32:
      [String] 2 = [Int32] 0000 0000 0000 0000 0000 0000 0000 0010
    • Shift the resulting Int32 variable left by 8 bits:
      0000 0000 1100 0000 1010 1000 0000 1010 << 8 --------------------------------------------- 1100 0000 1010 1000 0000 1010 0000 0000
    • Add IP address byte to the result:
      1100 0000 1010 1000 0000 1010 0000 0000 OR 0000 0000 0000 0000 0000 0000 0000 0010 --------------------------------------------- 1100 0000 1010 1000 0000 1010 0000 0010
  4. Return the result — 1100 0000 1010 1000 0000 1010 0000 0010, stored in $IPAddress.

Using the function: checking whether the IPv4 address belongs to the network

Here is an example of how we can use the created function. Let’s say we want to check whether the IP address belongs to the network. For instance, does the address 172.16.27.2 fall into the range of addresses of the network 172.16.24.0/22? In order to do such check, let’s create a couple more functions:

# Create Int32 with mask of the specified length. # Parameters: # MaskLength — length of the mask. Must be in range from 1 to 32 (inclusively) # Returns: # Int32 with mask of the specified length function Create-MaskInt { param ( [Parameter(Mandatory)] [ValidateRange(1, 32)] [int] $MaskLength ) return [int] "0xFFFFFFFF" -shl (32 - $MaskLength) } # Check whether IP address belongs to the specified network. # Parameters: # IPAddress — IP address to check, for example: "192.168.10.2" # Network — network address and mask, for example: "192.168.10.0/24" # Returns: # $true, if the address belongs to the specified network # $false, if the address does not belong to the specified network function Test-IfIPAddressBelongsToNetwork { param ( [Parameter(Mandatory)] [ValidatePattern( "^(0|[1-9]\d?|1\d\d|2[0-4]\d|25[0-5])(\.(0|[1-9]\d?|1\d\d|2[0-4]\d|25[0-5])){3}$" )] [string] $IPAddress ,[Parameter(Mandatory)] [ValidatePattern( "^(0|[1-9]\d?|1\d\d|2[0-4]\d|25[0-5])(\.(0|[1-9]\d?|1\d\d|2[0-4]\d|25[0-5])){3}/(\d|[1-2]\d?|3[0-2])$" )] [string] $Network ) $IPAddressInt = Convert-StringIPToIntIP -IPAddressString $IPAddress $NetworkAddressInt = Convert-StringIPToIntIP -IPAddressString $Network.Split("/")[0] $MaskInt = Create-MaskInt -MaskLength $Network.Split("/")[1] return ($IPAddressInt -band $MaskInt) -eq ($NetworkAddressInt -band $MaskInt) }

Now we can use this function to do some simple checks:

PS C:\> Test-IfIPAddressBelongsToNetwork -IPAddress "172.16.27.2" -Network "172.16.24.0/22" True
PS C:\> Test-IfIPAddressBelongsToNetwork -IPAddress "172.16.28.2" -Network "172.16.24.0/22" False

Or something more complex:

$Networks = @( "172.16.160.0/20" "172.16.228.0/22" ) $IPAddresses = @( "172.16.156.2" "172.16.164.2" "172.16.172.2" "172.16.187.2" "172.16.226.2" "172.16.228.2" "172.16.231.2" "172.16.236.2" ) # Select IP addresses that belong to the specified networks $IPAddresses | where { [Array]::Find( $Networks, [System.Predicate[string]] { param ($Network) Test-IfIPAddressBelongsToNetwork -IPAddress $_ -Network $Network } ) } # Select IP addresses that do not belong to the specified networks $IPAddresses | where { -not [Array]::Find( $Networks, [System.Predicate[string]] { param ($Network) Test-IfIPAddressBelongsToNetwork -IPAddress $_ -Network $Network } ) }

Select IP addresses that belong to the specified networks:

PS C:\> $IPAddresses | where { >> [Array]::Find( >> $Networks, >> [System.Predicate[string]] { >> param ($Network) >> Test-IfIPAddressBelongsToNetwork -IPAddress $_ -Network $Network >> } >> ) >> } 172.16.164.2 172.16.172.2 172.16.228.2 172.16.231.2

Select IP addresses that do not belong to the specified networks:

PS C:\> $IPAddresses | where { >> -not [Array]::Find( >> $Networks, >> [System.Predicate[string]] { >> param ($Network) >> Test-IfIPAddressBelongsToNetwork -IPAddress $_ -Network $Network >> } >> ) >> } 172.16.156.2 172.16.187.2 172.16.226.2 172.16.236.2