<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Indented! &#187; Subnet Math</title>
	<atom:link href="http://www.indented.co.uk/index.php/tag/subnet-math/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.indented.co.uk</link>
	<description></description>
	<lastBuildDate>Fri, 02 Jul 2010 10:45:15 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>IPv4 subnet math with PowerShell</title>
		<link>http://www.indented.co.uk/index.php/2010/01/23/powershell-subnet-math/</link>
		<comments>http://www.indented.co.uk/index.php/2010/01/23/powershell-subnet-math/#comments</comments>
		<pubDate>Sat, 23 Jan 2010 15:35:10 +0000</pubDate>
		<dc:creator>Chris</dc:creator>
				<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Subnet Math]]></category>

		<guid isPermaLink="false">http://www.indented.co.uk/?p=1370</guid>
		<description><![CDATA[Written to complement the VbScript version of this post. This collection of functions handles subnet math in PowerShell. Download all the functions and examples at once: Net-SubnetMath.ps1 Convert an IP to binary This function uses System.Convert to change each octet of an IP address into it&#8217;s binary form. PadLeft is used to add leading zero&#8217;s [...]


No related posts.

Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.]]></description>
			<content:encoded><![CDATA[<p>Written to complement the <a href='http://www.indented.co.uk/index.php/2008/10/21/vbscript-subnet-math/'>VbScript version</a> of this post. This collection of functions handles subnet math in PowerShell.</p>
<p>Download all the functions and examples at once: <a href='http://www.indented.co.uk/wp-content/uploads/2010/01/Net-SubnetMath.ps1_.txt'>Net-SubnetMath.ps1</a><br />
<span id="more-1370"></span></p>
<h3>Convert an IP to binary</h3>
<p>This function uses System.Convert to change each octet of an IP address into it&#8217;s binary form. PadLeft is used to add leading zero&#8217;s if required.</p>
<pre class="brush: powershell;">
Function ConvertTo-BinaryIP( [String]$IP ) {

  $IPAddress = [Net.IPAddress]::Parse($IP)

  Return [String]::Join('.',
    $( $IPAddress.GetAddressBytes() | %{
      [Convert]::ToString($_, 2).PadLeft(8, '0') } ))
}
</pre>
<h3>Convert an IP to a 32-bit decimal</h3>
<p>Allows conversion of an IP Address to an unsigned 32-bit integer.</p>
<pre class="brush: powershell;">
Function ConvertTo-DecimalIP( [String]$IP ) {

  $IPAddress = [Net.IPAddress]::Parse($IP)
  $i = 3
  $IPAddress.GetAddressBytes() | %{
    $DecimalIP += $_ * [Math]::Pow(256, $i); $i-- }

  Return [UInt32]$DecimalIP
}
</pre>
<h3>Convert a decimal number or binary IP to a dotted IP</h3>
<p>Used to switch a decimal or binary IP back to the more common dotted decimal format. The function uses a simple pair of regular expressions to determine which format is presented.</p>
<pre class="brush: powershell;">
Function ConvertTo-DottedDecimalIP( [String]$IP ) {

  Switch -RegEx ($IP) {
    &quot;([01]{8}\.){3}[01]{8}&quot; {

      Return [String]::Join('.', $( $IP.Split('.') | %{
        [Convert]::ToInt32($_, 2) } ))
    }
    &quot;\d&quot; {

      $IP = [UInt32]$IP
      $DottedIP = $( For ($i = 3; $i -gt -1; $i--) {
        $Remainder = $IP % [Math]::Pow(256, $i)
        ($IP - $Remainder) / [Math]::Pow(256, $i)
        $IP = $Remainder
       } )

      Return [String]::Join('.', $DottedIP)
    }
    default {
      Write-Error &quot;Cannot convert this format&quot;
    }
  }
}
</pre>
<h3>Convert a subnet mask to a mask length</h3>
<p>Occasionally it is desirable to calculate the subnet mask bit length. This can be done using the following.</p>
<pre class="brush: powershell;">
Function ConvertTo-MaskLength( [String]$Mask ) {

  $IPMask = [Net.IPAddress]::Parse($Mask)
  $Bits = &quot;$( $IPMask.GetAddressBytes() | %{
    [Convert]::ToString($_, 2) } )&quot; -Replace &quot;[\s0]&quot;

  Return $Bits.Length
}
</pre>
<h3>Convert a mask length to a subnet mask</h3>
<p>To a dotted decimal IP via binary and an unsigned 32-bit integer.</p>
<pre class="brush: powershell;">
Function ConvertTo-Mask( [Byte]$MaskLength ) {

  Return ConvertTo-DottedDecimalIP ([Convert]::ToUInt32(
    $((&quot;1&quot; * $MaskLength).PadRight(32, &quot;0&quot;)), 2))
}
</pre>
<h3>Calculate the subnet network address</h3>
<p>The functions above can be used with along with a bitwise AND operation against an IP address and subnet mask to calculate the network address.</p>
<p>Note that this function includes calls to both ConvertTo-DottedDecimalIP and ConvertTo-DecimalIP.</p>
<pre class="brush: powershell;">
Function Get-NetworkAddress( [String]$IP, [String]$Mask ) {

  Return ConvertTo-DottedDecimalIP $(
    (ConvertTo-DecimalIP $IP) -BAnd
    (ConvertTo-DecimalIP $Mask))
}
</pre>
<h3>Calculate the subnet broadcast address</h3>
<p>The function is right at the bottom, the explanation is, of course, entirely optional.</p>
<p>Getting to the Broadcast Address is a bit more complicated than the Network Address. A Bitwise Or is executed against an Inverted Subnet Mask. For example, the Inverted form of 255.255.255.0 is 0.0.0.255.</p>
<p>Inverting the decimal value of the subnet mask can be performed using BNot, the Complement Operator (see Get-Help About_Comparison_Operators).</p>
<p>Unfortunately BNot only returns a signed 64-bit integer (in the range -9223372036854775808 to 9223372036854775807).</p>
<pre class="brush: plain;">
PS C:\&gt; $Value = ConvertTo-DecimalIP 255.255.255.0; $Value
4294967040
PS C:\&gt; $Value.GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     UInt32                                   System.ValueType

PS C:\&gt; $Inverted = -BNot $Value; $Inverted
-4294967041
PS C:\&gt; $Inverted.GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Int64                                    System.ValueType

PS C:\&gt; # Convert to Binary (Base 2)
PS C:\&gt; [Convert]::ToString($Inverted, 2)
1111111111111111111111111111111100000000000000000000000011111111
</pre>
<p>The first 32 bits have are 1 (feel free to count). This happens because of the implicit conversion between UInt32 and Int64. Those 32 leading 1&#8242;s must go; Back to Binary And.</p>
<pre class="brush: plain;">
PS C:\&gt; $Inverted -BAnd [UInt32]::MaxValue
255
</pre>
<p>The operation takes advantage of the implicit conversion between types to get [UInt32]::MaxValue and to an Int64 type. As a result, this is what BAnd did:</p>
<pre class="brush: plain;">
1: 11111111 11111111 11111111 11111111 00000000 00000000 00000000 11111111
2: 00000000 00000000 00000000 00000000 11111111 11111111 11111111 11111111
3: 00000000 00000000 00000000 00000000 00000000 00000000 00000000 11111111
</pre>
<p>Where 1 is the Int64 value from -BNot, 2 is the implicit conversion of [Int32]::MaxValue to Int64, and 3 is the result of the And operation. Finally, the resulting value can be implicitly (or explicitly) converted back to UInt32.</p>
<p>A very long explanation for a very short function.</p>
<pre class="brush: powershell;">
Function Get-BroadcastAddress( [String]$IP, [String]$Mask ) {

  Return ConvertTo-DottedDecimalIP $(
    (ConvertTo-DecimalIP $IP) -BOr
    ((-BNot (ConvertTo-DecimalIP $Mask)) -BAnd [UInt32]::MaxValue))
}
</pre>
<h3>Get-NetworkInfo</h3>
<p>Putting the functions above to work, providing a summary of an IP address range.</p>
<pre class="brush: powershell;">
Function Get-NetworkInfo( [String]$IP, [String]$Mask ) {
  If ($IP.Contains(&quot;/&quot;))
  {
    $Temp = $IP.Split(&quot;/&quot;)
    $IP = $Temp[0]
    $Mask = $Temp[1]
  }

  If (!$Mask.Contains(&quot;.&quot;))
  {
    $Mask = ConvertTo-Mask $Mask
  }

  $DecimalIP = ConvertTo-DecimalIP $IP
  $DecimalMask = ConvertTo-DecimalIP $Mask

  $Network = $DecimalIP -BAnd $DecimalMask
  $Broadcast = $DecimalIP -BOr
    ((-BNot $DecimalMask) -BAnd [UInt32]::MaxValue)
  $NetworkAddress = ConvertTo-DottedDecimalIP $Network
  $RangeStart = ConvertTo-DottedDecimalIP ($Network + 1)
  $RangeEnd = ConvertTo-DottedDecimalIP ($Broadcast - 1)
  $BroadcastAddress = ConvertTo-DottedDecimalIP $Broadcast
  $MaskLength = ConvertTo-MaskLength $Mask

  $BinaryIP = ConvertTo-BinaryIP $IP; $Private = $False
  Switch -RegEx ($BinaryIP)
  {
    &quot;^1111&quot;  { $Class = &quot;E&quot;; $SubnetBitMap = &quot;1111&quot; }
    &quot;^1110&quot;  { $Class = &quot;D&quot;; $SubnetBitMap = &quot;1110&quot; }
    &quot;^110&quot;   {
      $Class = &quot;C&quot;
      If ($BinaryIP -Match &quot;^11000000.10101000&quot;) { $Private = $True } }
    &quot;^10&quot;    {
      $Class = &quot;B&quot;
      If ($BinaryIP -Match &quot;^10101100.0001&quot;) { $Private = $True } }
    &quot;^0&quot;     {
      $Class = &quot;A&quot;
      If ($BinaryIP -Match &quot;^00001010&quot;) { $Private = $True } }
   }   

  $NetInfo = New-Object Object
  Add-Member NoteProperty &quot;Network&quot; -Input $NetInfo -Value $NetworkAddress
  Add-Member NoteProperty &quot;Broadcast&quot; -Input $NetInfo -Value $BroadcastAddress
  Add-Member NoteProperty &quot;Range&quot; -Input $NetInfo `
    -Value &quot;$RangeStart - $RangeEnd&quot;
  Add-Member NoteProperty &quot;Mask&quot; -Input $NetInfo -Value $Mask
  Add-Member NoteProperty &quot;MaskLength&quot; -Input $NetInfo -Value $MaskLength
  Add-Member NoteProperty &quot;Hosts&quot; -Input $NetInfo `
    -Value $($Broadcast - $Network - 1)
  Add-Member NoteProperty &quot;Class&quot; -Input $NetInfo -Value $Class
  Add-Member NoteProperty &quot;IsPrivate&quot; -Input $NetInfo -Value $Private

  Return $NetInfo
}
</pre>
<h3>Get-NetworkRange</h3>
<p>Calculate each host address within the network range.</p>
<pre class="brush: powershell;">
Function Get-NetworkRange( [String]$IP, [String]$Mask ) {
  If ($IP.Contains(&quot;/&quot;))
  {
    $Temp = $IP.Split(&quot;/&quot;)
    $IP = $Temp[0]
    $Mask = $Temp[1]
  }

  If (!$Mask.Contains(&quot;.&quot;))
  {
    $Mask = ConvertTo-Mask $Mask
  }

  $DecimalIP = ConvertTo-DecimalIP $IP
  $DecimalMask = ConvertTo-DecimalIP $Mask

  $Network = $DecimalIP -BAnd $DecimalMask
  $Broadcast = $DecimalIP -BOr ((-BNot $DecimalMask) -BAnd [UInt32]::MaxValue)

  For ($i = $($Network + 1); $i -lt $Broadcast; $i++) {
    ConvertTo-DottedDecimalIP $i
  }
}
</pre>
<h3>Examples</h3>
<pre class="brush: powershell;">
# Use of Convert Functions
ConvertTo-BinaryIP 192.168.1.1
ConvertTo-DecimalIP 192.168.1.1
ConvertTo-DottedDecimalIP 11000000.10101000.00000001.00000001
ConvertTo-DottedDecimalIP 3232235777
ConvertTo-MaskLength 255.255.128.0
ConvertTo-Mask 17

# Use of Network and Broadcast Address Functions
Get-NetworkAddress 192.168.1.1 255.255.255.0
Get-BroadcastAddress 192.168.1.1 255.255.255.0

# Use of Network Info
Get-NetworkInfo 229.168.1.1 255.255.248.0
Get-NetworkInfo 172.16.1.243 18
Get-NetworkInfo 10.0.0.3/14

# Use of Network Range
Get-NetworkRange 192.168.1.5 255.255.255.248
Get-NetworkRange 172.18.0.23 30
Get-NetworkRange 172.18.0.23/29
</pre>


<p>No related posts.</p>
<p>Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://www.indented.co.uk/index.php/2010/01/23/powershell-subnet-math/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>IPv4 subnet math with VbScript</title>
		<link>http://www.indented.co.uk/index.php/2008/10/21/vbscript-subnet-math/</link>
		<comments>http://www.indented.co.uk/index.php/2008/10/21/vbscript-subnet-math/#comments</comments>
		<pubDate>Tue, 21 Oct 2008 12:23:55 +0000</pubDate>
		<dc:creator>Chris</dc:creator>
				<category><![CDATA[VbScript]]></category>
		<category><![CDATA[IP Conversion]]></category>
		<category><![CDATA[Subnet Math]]></category>
		<category><![CDATA[vbs]]></category>

		<guid isPermaLink="false">http://www.highorbit.co.uk/?p=270</guid>
		<description><![CDATA[At times it can be very convenient to be able to work with IP Addresses and subnetting in VbScript. This collection of functions handles subnet math in VbScript. A PowerShell version of these functions can be found here. Convert an IP to binary This function performs a bitwise comparison (AND) with each octet in the [...]


No related posts.

Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.]]></description>
			<content:encoded><![CDATA[<p>At times it can be very convenient to be able to work with IP Addresses and subnetting in VbScript. This collection of functions handles subnet math in VbScript.</p>
<p>A PowerShell version of these functions can be found <a href='http://www.indented.co.uk/index.php/2010/01/23/powershell-subnet-math/'>here</a>.<br />
<span id="more-270"></span></p>
<h3>Convert an IP to binary</h3>
<p>This function performs a bitwise comparison (AND) with each octet in the original IP to determine if each power of two is present starting with the highest, 128 returning the binary version of any IP address.</p>
<pre class="brush: vb;">
Function ConvertIPToBinary(strIP)
  ' Converts an IP Address into Binary

  Dim arrOctets : arrOctets = Split(strIP, &quot;.&quot;)
  Dim i
  For i = 0 to UBound(arrOctets)
    Dim intOctet : intOctet = CInt(arrOctets(i))
    Dim strBinOctet : strBinOctet = &quot;&quot;
    Dim j
    For j = 0 To 7
      If intOctet And (2^(7 - j)) Then
        strBinOctet = strBinOctet &amp; &quot;1&quot;
      Else
        strBinOctet = strBinOctet &amp; &quot;0&quot;
      End If
    Next
    arrOctets(i) = strBinOctet
  Next
  ConvertIPToBinary = Join(arrOctets, &quot;.&quot;)
End Function
</pre>
<h3>Convert a binary IP to a decimal IP</h3>
<p>It is important to be able to convert back into the familiar form of the IP address, this calculates the decimal form of an IP address based on the binary.</p>
<pre class="brush: vb;">
Function ConvertBinIPToDecimal(strBinIP)
  ' Convert binary form of an IP back to decimal

  Dim arrOctets : arrOctets = Split(strBinIP, &quot;.&quot;)
  Dim i
  For i = 0 to UBound(arrOctets)
    Dim intOctet : intOctet = 0
    Dim j
    For j = 0 to 7
      Dim intBit : intBit = CInt(Mid(arrOctets(i), j + 1, 1))
      If intBit = 1 Then
        intOctet = intOctet + 2^(7 - j)
      End If
    Next
    arrOctets(i) = CStr(intOctet)
  Next

  ConvertBinIPToDecimal = Join(arrOctets, &quot;.&quot;)
End Function
</pre>
<h3>Convert a subnet mask to a mask length</h3>
<p>Occasionally it is desirable to calculate the subnet mask bit length. This can be done using the following.</p>
<pre class="brush: vb;">
Function MaskLength(strMask)
  ' Converts an subnet mask into a mask length in bits

  Dim arrOctets : arrOctets = Split(strMask, &quot;.&quot;)
  Dim i
  For i = 0 to UBound(arrOctets)
    Dim intOctet : intOctet = CInt(arrOctets(i))
    Dim j, intMaskLength
    For j = 0 To 7
      If intOctet And (2^(7 -j)) Then
        intMaskLength = intMaskLength + 1
      End If
    Next
  Next
  MaskLength = intMaskLength
End Function
</pre>
<h3>Convert a mask length to a subnet mask</h3>
<pre class="brush: vb;">
Function MaskLengthToIP(intMask)
  ' Converts a mask length to the decimal format mask

  Dim arrOctets(3)
  Dim intFullOctets : intFullOctets = (intMask - (intMask Mod 8)) / 8
  Dim i
  For i = 0 To (intFullOctets - 1)
    arrOctets(i) = &quot;255&quot;
  Next

  Dim intPartialOctetLen : intPartialOctetLen = intMask Mod 8
  Dim j
  If intPartialOctetLen &gt; 0 Then
    Dim intOctet
    For j = 0 To (intPartialOctetLen - 1)
      intOctet = intOctet + 2^(7 - j)
    Next
    arrOctets(i) = intOctet : i = i + 1
  End If

  For j = i To 3
    arrOctets(j) = &quot;0&quot;
  Next

  MaskLengthToIP = Join(arrOctets, &quot;.&quot;)
End Function
</pre>
<h3>Calculate the subnet network address</h3>
<p>The functions above can be used with along with a bitwise AND operation against an IP address and subnet mask to calculate the network address.</p>
<p>Note that this function includes calls to both ConvertIPToBinary and ConvertBinIPToDecimal.</p>
<pre class="brush: vb;">
Function CalcNetworkAddress(strIP, strMask)
  ' Generates the Network Address from the IP and Mask

  ' Conversion of IP and Mask to binary
  Dim strBinIP : strBinIP = ConvertIPToBinary(strIP)
  Dim strBinMask : strBinMask = ConvertIPToBinary(strMask)

  ' Bitwise AND operation (except for the dot)
  Dim i, strBinNetwork
  For i = 1 to Len(strBinIP)
    Dim strIPBit : strIPBit = Mid(strBinIP, i, 1)
    Dim strMaskBit : strMaskBit = Mid(strBinMask, i, 1)

    If strIPBit = &quot;1&quot; And strMaskBit = &quot;1&quot; Then
      strBinNetwork = strBinNetwork &amp; &quot;1&quot;
    ElseIf strIPBit = &quot;.&quot; Then
      strBinNetwork = strBinNetwork &amp; strIPBit
    Else
      strBinNetwork = strBinNetwork &amp; &quot;0&quot;
    End If
  Next

  ' Conversion of Binary IP to Decimal
  CalcNetworkAddress= ConvertBinIPToDecimal(strBinNetwork)
End Function
</pre>
<h3>Calculate the subnet broadcast address</h3>
<p>To calculate the broadcast address requires a modification of the CalcNetworkAddress function above. This time, it sets anything that is not covered by the mask to 1.</p>
<p>Note that this function includes calls to both ConvertIPToBinary and ConvertBinIPToDecimal.</p>
<pre class="brush: vb;">
Function CalcBroadcastAddress(strIP, strMask)
  ' Generates the Broadcast Address from the IP and Mask

  ' Conversion of IP and Mask to binary
  Dim strBinIP : strBinIP = ConvertIPToBinary(strIP)
  Dim strBinMask : strBinMask = ConvertIPToBinary(strMask)

  ' Set each unmasked bit to 1
  Dim i, strBinBroadcast
  For i = 1 to Len(strBinIP)
    Dim strIPBit : strIPBit = Mid(strBinIP, i, 1)
    Dim strMaskBit : strMaskBit = Mid(strBinMask, i, 1)

    If strIPBit = &quot;1&quot; Or strMaskBit = &quot;0&quot; Then
      strBinBroadcast = strBinBroadcast &amp; &quot;1&quot;
    ElseIf strIPBit = &quot;.&quot; Then
      strBinBroadcast = strBinBroadcast &amp; strIPBit
    Else
      strBinBroadcast = strBinBroadcast &amp; &quot;0&quot;
    End If
  Next

  ' Conversion of Binary IP to Decimal
  CalcBroadcastAddress = ConvertBinIPToDecimal(strBinBroadcast)
End Function
</pre>


<p>No related posts.</p>
<p>Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://www.indented.co.uk/index.php/2008/10/21/vbscript-subnet-math/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
	</channel>
</rss>
