<?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>Mon, 17 Oct 2011 19:03:30 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Sorting by IP address</title>
		<link>http://www.indented.co.uk/index.php/2011/10/14/sorting-by-ip-address/</link>
		<comments>http://www.indented.co.uk/index.php/2011/10/14/sorting-by-ip-address/#comments</comments>
		<pubDate>Fri, 14 Oct 2011 10:53:41 +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=1630</guid>
		<description><![CDATA[Sorting an array of IP addresses is one of those things that&#8217;s not quite as clean and simple as would be nice. Fortunately, the process can be simplified greatly by converting an IP address to decimal for the sort operation. To do this, I like to use ConvertTo-DecimalIP from my NetShell module (or my collection [...]
Related posts:<ol>
<li><a href='http://www.indented.co.uk/index.php/2011/10/13/more-ipv4-subnet-maths-with-powershell/' rel='bookmark' title='More IPv4 subnet maths with PowerShell'>More IPv4 subnet maths with PowerShell</a> <small>I&#8217;ve been extended and upgrading my library of network functions...</small></li>
</ol>

Related posts brought to you by <a href='http://yarpp.org'>Yet Another Related Posts Plugin</a>.]]></description>
			<content:encoded><![CDATA[<p>Sorting an array of IP addresses is one of those things that&#8217;s not quite as clean and simple as would be nice.<br />
<span id="more-1630"></span><br />
Fortunately, the process can be simplified greatly by converting an IP address to decimal for the sort operation. To do this, I like to use ConvertTo-DecimalIP from my NetShell module (or my collection of subnet maths functions).</p>
<pre class="brush: powershell; title: ; notranslate">
&quot;10.1.10.10&quot;, &quot;192.168.1.42&quot;, &quot;172.16.1.1&quot;, &quot;127.0.0.1&quot; | Sort-Object { ConvertTo-DecimalIP $_ }
</pre>
<p>Short and simple.</p>
<p>Related posts:<ol>
<li><a href='http://www.indented.co.uk/index.php/2011/10/13/more-ipv4-subnet-maths-with-powershell/' rel='bookmark' title='More IPv4 subnet maths with PowerShell'>More IPv4 subnet maths with PowerShell</a> <small>I&#8217;ve been extended and upgrading my library of network functions...</small></li>
</ol></p>
<p>Related posts brought to you by <a href='http://yarpp.org'>Yet Another Related Posts Plugin</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://www.indented.co.uk/index.php/2011/10/14/sorting-by-ip-address/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>More IPv4 subnet maths with PowerShell</title>
		<link>http://www.indented.co.uk/index.php/2011/10/13/more-ipv4-subnet-maths-with-powershell/</link>
		<comments>http://www.indented.co.uk/index.php/2011/10/13/more-ipv4-subnet-maths-with-powershell/#comments</comments>
		<pubDate>Thu, 13 Oct 2011 11:55:19 +0000</pubDate>
		<dc:creator>Chris</dc:creator>
				<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[subnet]]></category>
		<category><![CDATA[Subnet Math]]></category>

		<guid isPermaLink="false">http://www.indented.co.uk/?p=1621</guid>
		<description><![CDATA[I&#8217;ve been extended and upgrading my library of network functions for some time now, I thought I&#8217;d post the functions that work directly with my original collection. These functions are also included in my NetShell module, I need to post an update to that very soon as well. ConvertTo-HexIP Sometimes being able to convert to [...]
No related posts.

Related posts brought to you by <a href='http://yarpp.org'>Yet Another Related Posts Plugin</a>.]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been extended and upgrading my library of network functions for some time now, I thought I&#8217;d post the functions that work directly with my <a href='http://www.indented.co.uk/index.php/2010/01/23/powershell-subnet-math/'>original collection</a>.<br />
<span id="more-1621"></span><br />
These functions are also included in my NetShell module, I need to post an update to that very soon as well.</p>
<h3>ConvertTo-HexIP</h3>
<p>Sometimes being able to convert to a hexadecimal format is useful, this little function does exactly that. The body is very simple; it uses the built in formatters.</p>
<pre class="brush: powershell; title: ; notranslate">
Function ConvertTo-HexIP {
  &lt;#
    .Synopsis
      Converts a dotted decimal IP address into a hexadecimal string.
    .Description
      ConvertTo-HexIP takes a dotted decimal IP and returns a single hexadecimal string value.
    .Parameter IPAddress
      An IP Address to convert.
  #&gt;

  [CmdLetBinding()]
  Param(
    [Parameter(Mandatory = $True, Position = 0, ValueFromPipeline = $True)]
    [Net.IPAddress]$IPAddress
  )

  Process {
    &quot;$($IPAddress.GetAddressBytes() | ForEach-Object { '{0:x2}' -f $_ })&quot; -Replace '\s'
  }
}
</pre>
<h3>ConvertFrom-HexIP</h3>
<p>And back again, using System.Convert.ToUInt32 with a base-16 value to get to UInt32, then a call to ConvertTo-DottedDecimalIP (from the original set).</p>
<pre class="brush: powershell; title: ; notranslate">
Function ConvertFrom-HexIP {
  &lt;#
    .Synopsis
      Converts a hexadecimal IP address into a dotted decimal string.
    .Description
      ConvertFrom-HexIP takes a hexadecimal string and returns a dotted decimal IP address.
    .Parameter IPAddress
      An IP Address to convert.
  #&gt;

  [CmdLetBinding()]
  Param(
    [Parameter(Mandatory = $True, Position = 0, ValueFromPipeline = $True)]
    [ValidatePattern('^[0-9a-f]{8}$')]
    [String]$IPAddress
  )

  Process {
    ConvertTo-DottedDecimalIP ([Convert]::ToUInt32($IPAddress, 16))
  }
}
</pre>
<h3>Get-NetworkSummary</h3>
<p>Get-NetworkSummary gets a bit of an improvement.</p>
<pre class="brush: powershell; title: ; notranslate">
Function Get-NetworkSummary {
  &lt;#
    .Synopsis
      Generates a summary of a network range
    .Description
      Get-NetworkSummary uses most of the IP conversion CmdLets to provide a summary of a network
      range from any IP address in the range and a subnet mask.
    .Parameter IPAddress
      Any IP address within the network range.
    .Parameter Network
      A network description in the format 1.2.3.4/24
    .Parameter SubnetMask
      The subnet mask for the network.
  #&gt;

  [CmdLetBinding(DefaultParameterSetName = &quot;IPAndMask&quot;)]
  Param(
    [Parameter(Mandatory = $True, Position = 0, ParameterSetName = &quot;IPAndMask&quot;, ValueFromPipeline = $True)]
    [Net.IPAddress]$IPAddress,

    [Parameter(Mandatory = $True, Position = 1, ParameterSetName = &quot;IPAndMask&quot;)]
    [Alias(&quot;Mask&quot;)]
    [Net.IPAddress]$SubnetMask,

    [Parameter(Mandatory = $True, ParameterSetName = &quot;CIDRNotation&quot;, ValueFromPipeline = $True)]
    [ValidatePattern('^(\d{1,3}\.){3}\d{1,3}[\\/]\d{1,2}$')]
    [String]$Network
  )

  Process {
    If ($PsCmdLet.ParameterSetName -eq 'CIDRNotation') {
      $Temp = $Network.Split(&quot;\/&quot;)
      $IPAddress = $Temp[0]
      $SubnetMask = ConvertTo-Mask $Temp[1]
    }

    $DecimalIP = ConvertTo-DecimalIP $IPAddress
    $DecimalMask = ConvertTo-DecimalIP $SubnetMask
    $DecimalNetwork =  $DecimalIP -BAnd $DecimalMask
    $DecimalBroadcast = $DecimalIP -BOr ((-BNot $DecimalMask) -BAnd [UInt32]::MaxValue)

    $NetworkSummary = New-Object PSObject -Property @{
      &quot;NetworkAddress&quot;   = (ConvertTo-DottedDecimalIP $DecimalNetwork);
      &quot;NetworkDecimal&quot;   = $DecimalNetwork
      &quot;BroadcastAddress&quot; = (ConvertTo-DottedDecimalIP $DecimalBroadcast);
      &quot;BroadcastDecimal&quot; = $DecimalBroadcast
      &quot;Mask&quot;             = $SubnetMask;
      &quot;MaskLength&quot;       = (ConvertTo-MaskLength $SubnetMask);
      &quot;MaskHexadecimal&quot;  = (ConvertTo-HexIP $SubnetMask);
      &quot;HostRange&quot;        = &quot;&quot;;
      &quot;NumberOfHosts&quot;    = ($DecimalBroadcast - $DecimalNetwork - 1);
      &quot;Class&quot;            = &quot;&quot;;
      &quot;IsPrivate&quot;        = $False}

    If ($NetworkSummary.MaskLength -lt 31) {
      $NetworkSummary.HostRange = [String]::Format(&quot;{0} - {1}&quot;,
        (ConvertTo-DottedDecimalIP ($DecimalNetwork + 1)),
        (ConvertTo-DottedDecimalIP ($DecimalBroadcast - 1)))
    }

    Switch -RegEx ($(ConvertTo-BinaryIP $IPAddress)) {
      &quot;^1111&quot;              { $NetworkSummary.Class = &quot;E&quot; }
      &quot;^1110&quot;              { $NetworkSummary.Class = &quot;D&quot; }
      &quot;^11000000.10101000&quot; { $NetworkSummary.Class = &quot;C&quot;; $NetworkSummary.IsPrivate = $True }
      &quot;^110&quot;               { $NetworkSummary.Class = &quot;C&quot; }
      &quot;^10101100.0001&quot;     { $NetworkSummary.Class = &quot;B&quot;; $NetworkSummary.IsPrivate = $True }
      &quot;^10&quot;                { $NetworkSummary.Class = &quot;B&quot; }
      &quot;^00001010&quot;          { $NetworkSummary.Class = &quot;A&quot;; $NetworkSummary.IsPrivate = $True }
      &quot;^0&quot;                 { $NetworkSummary.Class = &quot;A&quot; }
    }   

    Return $NetworkSummary
  }
}
</pre>
<h3>Get-NetworkRange</h3>
<p>And so does Get-NetworkRange.</p>
<pre class="brush: powershell; title: ; notranslate">
Function Get-NetworkRange {
  &lt;#
    .Synopsis
      Generates IP addresses within the specified network.
    .Description
      Get-NetworkRange finds the network and broadcast address as decimal values then starts a
      counter between the two, returning Net.IPAddress for each.
    .Parameter IPAddress
      Any IP address within the network range.
    .Parameter Network
      A network description in the format 1.2.3.4/24
    .Parameter SubnetMask
      The subnet mask for the network.
  #&gt;

  [CmdLetBinding(DefaultParameterSetName = &quot;IPAndMask&quot;)]
  Param(
    [Parameter(Mandatory = $True, Position = 0, ParameterSetName = &quot;IPAndMask&quot;, ValueFromPipeline = $True)]
    [Net.IPAddress]$IPAddress, 

    [Parameter(Mandatory = $True, Position = 1, ParameterSetName = &quot;IPAndMask&quot;)]
    [Alias(&quot;Mask&quot;)]
    [Net.IPAddress]$SubnetMask,

    [Parameter(Mandatory = $True, ParameterSetName = &quot;CIDRNotation&quot;, ValueFromPipeline = $True)]
    [ValidatePattern('^(\d{1,3}\.){3}\d{1,3}[\\/]\d{1,2}$')]
    [String]$Network
  )

  Process {
    If ($PsCmdLet.ParameterSetName -eq 'CIDRNotation') {
      $Temp = $Network.Split(&quot;\/&quot;)
      $IPAddress = $Temp[0]
      $SubnetMask = ConvertTo-Mask $Temp[1]
    }

    $DecimalIP = ConvertTo-DecimalIP $IPAddress
    $DecimalMask = ConvertTo-DecimalIP $SubnetMask

    $DecimalNetwork = $DecimalIP -BAnd $DecimalMask
    $DecimalBroadcast = $DecimalIP -BOr ((-BNot $DecimalMask) -BAnd [UInt32]::MaxValue)

    For ($i = $($DecimalNetwork + 1); $i -lt $DecimalBroadcast; $i++) {
      ConvertTo-DottedDecimalIP $i
    }
  }
}
</pre>
<h3>Get-Subnets</h3>
<p>I ran into a need to calculate a list of subnets of a specific length within a super-net, this function does just that.</p>
<pre class="brush: powershell; title: ; notranslate">
Function Get-Subnets {
  &lt;#
    .Synopsis
      Generates a list of subnets for a given network range
    .Description
      Generates a list of subnets for a given network range using either the address class or a
      user-specified value.
    .Parameter NetworkAddress
      Any address in the supernet range.
    .Parameter SubnetMask
      The desired mask, determines the size of the resulting subnet. Must be a valid subnet mask.
    .Parameter SupernetLength
      By default Get-Subnets uses the address class to determine the size of the supernet. Where the
      supernet describes the range of addresses being split.
  #&gt;

  [CmdLetBinding(DefaultParameterSetName = &quot;PS1&quot;)]
  Param(
    [Parameter(Mandatory = $True, Position = 0, ParameterSetName = &quot;IPAndMask&quot;, ValueFromPipeline = $True)]
    [Net.IPAddress]$IPAddress, 

    [Parameter(Mandatory = $True, Position = 1, ParameterSetName = &quot;IPAndMask&quot;)]
    [Alias(&quot;Mask&quot;)]
    [Net.IPAddress]$SubnetMask,

    [Parameter(Mandatory = $True, ParameterSetName = &quot;CIDRNotation&quot;, ValueFromPipeline = $True)]
    [ValidatePattern('^(\d{1,3}\.){3}\d{1,3}[\\/]\d{1,2}$')]
    [String]$Network,

    [ValidateRange(1, 32)]
    [UInt32]$SupernetLength
  )

  Process {
    If ($PsCmdLet.ParameterSetName -eq 'CIDRNotation') {
      $Temp = $Network.Split(&quot;\/&quot;)
      $IPAddress = $Temp[0]
      $SubnetMask = ConvertTo-Mask $Temp[1]
    } Else {
      $SubnetLength = ConvertTo-MaskLength $SubnetMask
    }

    If (!$SupernetLength) {
      $SupernetLength = Switch -RegEx ($(ConvertTo-BinaryIP $IPAddress)) {
        &quot;^110&quot;  { 24 }
        &quot;^10&quot;   { 16 }
        &quot;^0&quot;    { 8 }
        default { 24 }
      }
    }
    If ($SupernetLength -gt $SubnetLength) {
      Write-Error &quot;Subnet is larger than supernet. Aborting&quot;
    }
    $SupernetMask = ConvertTo-Mask $SupernetLength

    $NumberOfNets = [Math]::Pow(2, ($SubnetLength - $SupernetLength))
    $NumberOfAddresses = [Math]::Pow(2, (32 - $SubnetLength))

    $SupernetAddress = Get-NetworkAddress $IPAddress $SupernetMask
    $DecimalAddress = ConvertTo-DecimalIP $SupernetAddress

    For ($i = 0; $i -lt $NumberOfNets; $i++) {
      $NetworkAddress = ConvertTo-DottedDecimalIP $DecimalAddress 

      &quot;&quot; | Select-Object @{n='NetworkAddress';e={ $NetworkAddress }},
        @{n='BroadcastAddress';e={ Get-BroadcastAddress $NetworkAddress $SubnetMask }},
        @{n='SubnetMask';e={ $SubnetMask }},
        @{n='HostAddresses';e={
          $NumberOfHosts = $NumberOfAddresses - 2
          If ($NumberOfHosts -lt 0) { 0 } Else { $NumberOfHosts } }}

      $DecimalAddress += $NumberOfAddresses
    }
  }
}
</pre>
<p>No related posts.</p>
<p>Related posts brought to you by <a href='http://yarpp.org'>Yet Another Related Posts Plugin</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://www.indented.co.uk/index.php/2011/10/13/more-ipv4-subnet-maths-with-powershell/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>NetShell</title>
		<link>http://www.indented.co.uk/index.php/2010/11/25/netshell/</link>
		<comments>http://www.indented.co.uk/index.php/2010/11/25/netshell/#comments</comments>
		<pubDate>Thu, 25 Nov 2010 19:56:50 +0000</pubDate>
		<dc:creator>Chris</dc:creator>
				<category><![CDATA[DHCP]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[smtp]]></category>
		<category><![CDATA[subnet]]></category>
		<category><![CDATA[Subnet Math]]></category>
		<category><![CDATA[SysLog]]></category>

		<guid isPermaLink="false">http://www.indented.co.uk/?p=1561</guid>
		<description><![CDATA[It&#8217;s been a while since I&#8217;ve posted, and since it&#8217;s almost Christmas I thought I&#8217;d better get on with it. Without further ado I want to post NetShell (I&#8217;m not very good at coming up with imaginative names). NetShell is a collection of 17 functions and a few supporting functions in a script module. Download [...]
No related posts.

Related posts brought to you by <a href='http://yarpp.org'>Yet Another Related Posts Plugin</a>.]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s been a while since I&#8217;ve posted, and since it&#8217;s almost Christmas I thought I&#8217;d better get on with it.</p>
<p>Without further ado I want to post NetShell (I&#8217;m not very good at coming up with imaginative names). NetShell is a collection of 17 functions and a few supporting functions in a script module. </p>
<p>Download <a href='http://www.indented.co.uk/wp-content/uploads/2011/05/NetShell.zip'>NetShell</a><br />
<span id="more-1561"></span><br />
Installation is a manual process, but not too hard. Open up Documents\WindowsPowerShell\Modules, extract the ZIP file. Make sure it includes the NetShell folder or it won&#8217;t work. The module is not currently signed, something else on the to-do list. Once it&#8217;s there, Import-Module NetShell and off you go.</p>
<p>It includes the following:</p>
<table>
<tr>
<td><b>ConvertTo-BinaryIP</b></td>
<td>Converts an IP address into a binary string</td>
</tr>
<tr>
<td><b>ConvertTo-Byte</b></td>
<td>A supporting function, a simple conversion of a string to a byte array (ASCII encoding)</td>
</tr>
<tr>
<td><b>ConvertTo-DecimalIP</b></td>
<td>Converts an IP address to 32-bit decimal number</td>
</tr>
<tr>
<td><b>ConvertTo-DottedDecimalIP</b></td>
<td>Converts a binary or 32-bit decimal back to an IP</td>
</tr>
<tr>
<td><b>ConvertTo-Mask</b></td>
<td>Converts from a mask length. For example, gets you from 22 to 255.255.252.0</td>
</tr>
<tr>
<td><b>ConvertTo-MaskLength</b></td>
<td>Converts from the IP form of a mask to the length</td>
</tr>
<tr>
<td><b>ConvertTo-String</b></td>
<td>Another supporting function, converts a byte array to a string (ASCII encoding)</td>
</tr>
<tr>
<td><b>Get-BroadcastAddress</b></td>
<td>Returns the broadcast address for the specified IP address and subnet mask</td>
</tr>
<tr>
<td><b>Get-NetworkAddress</b></td>
<td>Returns the network address for the specified IP address and subnet mask</td>
</tr>
<tr>
<td><b>Get-NetworkRange</b></td>
<td>Returns every IP within the specified range</td>
</tr>
<tr>
<td><b>Get-NetworkSummary</b></td>
<td>Everything about an IP address and mask I considered useful</td>
</tr>
<tr>
<td><b>New-DhcpDiscoverPacket</b></td>
<td>A supporting function for Send-DhcpDiscover. Creates the packet to send (a large byte array)</td>
</tr>
<tr>
<td><b>New-Socket</b></td>
<td>Creates an instance of System.Net.Sockets.Socket, an arbitrary network socket to do with as you please.</td>
</tr>
<tr>
<td><b>New-SysLogDateTime</b></td>
<td>A supporting function to create a DateTime string in the format SysLog likes.</td>
</tr>
<tr>
<td><b>Read-DhcpOption</b></td>
<td>A supporting function to read off an Option from a DHCP packet. Needs to be fed the Extended.BinaryReader class at the top of the module.</td>
</tr>
<tr>
<td><b>Read-DhcpPacket</b></td>
<td>Creates and uses an instance of Extended.BinaryReader to process a DHCP packet and translate the fields.</td>
</tr>
<tr>
<td><b>Receive-Bytes</b></td>
<td>Receives a stream of bytes from the network using a socket</td>
</tr>
<tr>
<td><b>Remove-Socket</b></td>
<td>Cleans up after New-Socket</td>
</tr>
<tr>
<td><b>Send-Bytes</b></td>
<td>Sends an arbitrary byte array over the network using a socket</td>
</tr>
<tr>
<td><b>Send-DhcpDiscover</b></td>
<td>Creates and sends a DHCPDISCOVER packet, then processes and returns the response</td>
</tr>
<tr>
<td><b>Start-Syslog</b></td>
<td>Starts a SysLog server. No termination for this one at the moment. Needs a bit more work.</td>
</tr>
<tr>
<td><b>Test-Smtp</b></td>
<td>Does the SMTP test you normally wind up doing with telnet, returning all the results along with the SMTP banner.</td>
</tr>
<tr>
<td><b>Test-SysLogDateTime</b></td>
<td>A supporting function to check the format of a DateTime that may or may not be present in a SysLog message.</td>
</tr>
<tr>
<td><b>Test-SysLogPRI</b></td>
<td>A supporting function to test of the PRI value in a SysLog message.</td>
</tr>
<tr>
<td><b>Test-TcpPort</b></td>
<td>Returns a boolean indicating whether or not the port connection succeeded.</td>
</tr>
</table>
<p>No related posts.</p>
<p>Related posts brought to you by <a href='http://yarpp.org'>Yet Another Related Posts Plugin</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://www.indented.co.uk/index.php/2010/11/25/netshell/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>IPv4 subnet maths 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 maths in PowerShell. 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 if required. Convert an IP to a 32-bit decimal [...]
No related posts.

Related posts brought to you by <a href='http://yarpp.org'>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 maths in PowerShell.<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; title: ; notranslate">
Function ConvertTo-BinaryIP {
  &lt;#
    .Synopsis
      Converts a Decimal IP address into a binary format.
    .Description
      ConvertTo-BinaryIP uses System.Convert to switch between decimal and binary format. The output from this function is dotted binary.
    .Parameter IPAddress
      An IP Address to convert.
  #&gt;

  [CmdLetBinding()]
  Param(
    [Parameter(Mandatory = $True, Position = 0, ValueFromPipeline = $True)]
    [Net.IPAddress]$IPAddress
  )

  Process {
    Return [String]::Join('.', $( $IPAddress.GetAddressBytes() |
      ForEach-Object { [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; title: ; notranslate">
Function ConvertTo-DecimalIP {
  &lt;#
    .Synopsis
      Converts a Decimal IP address into a 32-bit unsigned integer.
    .Description
      ConvertTo-DecimalIP takes a decimal IP, uses a shift-like operation on each octet and returns a single UInt32 value.
    .Parameter IPAddress
      An IP Address to convert.
  #&gt;

  [CmdLetBinding()]
  Param(
    [Parameter(Mandatory = $True, Position = 0, ValueFromPipeline = $True)]
    [Net.IPAddress]$IPAddress
  )

  Process {
    $i = 3; $DecimalIP = 0;
    $IPAddress.GetAddressBytes() | ForEach-Object { $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 set of regular expressions to determine which format is presented.</p>
<pre class="brush: powershell; title: ; notranslate">
Function ConvertTo-DottedDecimalIP {
  &lt;#
    .Synopsis
      Returns a dotted decimal IP address from either an unsigned 32-bit integer or a dotted binary string.
    .Description
      ConvertTo-DottedDecimalIP uses a regular expression match on the input string to convert to an IP address.
    .Parameter IPAddress
      A string representation of an IP address from either UInt32 or dotted binary.
  #&gt;

  [CmdLetBinding()]
  Param(
    [Parameter(Mandatory = $True, Position = 0, ValueFromPipeline = $True)]
    [String]$IPAddress
  )

  Process {
    Switch -RegEx ($IPAddress) {
      &quot;([01]{8}\.){3}[01]{8}&quot; {
        Return [String]::Join('.', $( $IPAddress.Split('.') | ForEach-Object { [Convert]::ToUInt32($_, 2) } ))
      }
      &quot;\d&quot; {
        $IPAddress = [UInt32]$IPAddress
        $DottedIP = $( For ($i = 3; $i -gt -1; $i--) {
          $Remainder = $IPAddress % [Math]::Pow(256, $i)
          ($IPAddress - $Remainder) / [Math]::Pow(256, $i)
          $IPAddress = $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; title: ; notranslate">
Function ConvertTo-MaskLength {
  &lt;#
    .Synopsis
      Returns the length of a subnet mask.
    .Description
      ConvertTo-MaskLength accepts any IPv4 address as input, however the output value
      only makes sense when using a subnet mask.
    .Parameter SubnetMask
      A subnet mask to convert into length
  #&gt;

  [CmdLetBinding()]
  Param(
    [Parameter(Mandatory = $True, Position = 0, ValueFromPipeline = $True)]
    [Alias(&quot;Mask&quot;)]
    [Net.IPAddress]$SubnetMask
  )

  Process {
    $Bits = &quot;$( $SubnetMask.GetAddressBytes() | ForEach-Object { [Convert]::ToString($_, 2) } )&quot; -Replace '[\s0]'

    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; title: ; notranslate">
Function ConvertTo-Mask {
  &lt;#
    .Synopsis
      Returns a dotted decimal subnet mask from a mask length.
    .Description
      ConvertTo-Mask returns a subnet mask in dotted decimal format from an integer value ranging
      between 0 and 32. ConvertTo-Mask first creates a binary string from the length, converts
      that to an unsigned 32-bit integer then calls ConvertTo-DottedDecimalIP to complete the operation.
    .Parameter MaskLength
      The number of bits which must be masked.
  #&gt;

  [CmdLetBinding()]
  Param(
    [Parameter(Mandatory = $True, Position = 0, ValueFromPipeline = $True)]
    [Alias(&quot;Length&quot;)]
    [ValidateRange(0, 32)]
    $MaskLength
  )

  Process {
    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; title: ; notranslate">
Function Get-NetworkAddress {
  &lt;#
    .Synopsis
      Takes an IP address and subnet mask then calculates the network address for the range.
    .Description
      Get-NetworkAddress returns the network address for a subnet by performing a bitwise AND
      operation against the decimal forms of the IP address and subnet mask. Get-NetworkAddress
      expects both the IP address and subnet mask in dotted decimal format.
    .Parameter IPAddress
      Any IP address within the network range.
    .Parameter SubnetMask
      The subnet mask for the network.
  #&gt;

  [CmdLetBinding()]
  Param(
    [Parameter(Mandatory = $True, Position = 0, ValueFromPipeline = $True)]
    [Net.IPAddress]$IPAddress,

    [Parameter(Mandatory = $True, Position = 1)]
    [Alias(&quot;Mask&quot;)]
    [Net.IPAddress]$SubnetMask
  )

  Process {
    Return ConvertTo-DottedDecimalIP ((ConvertTo-DecimalIP $IPAddress) -BAnd (ConvertTo-DecimalIP $SubnetMask))
  }
}
</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; title: ; notranslate">
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; title: ; notranslate">
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; title: ; notranslate">
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; title: ; notranslate">
Function Get-BroadcastAddress {
  &lt;#
    .Synopsis
      Takes an IP address and subnet mask then calculates the broadcast address for the range.
    .Description
      Get-BroadcastAddress returns the broadcast address for a subnet by performing a bitwise AND
      operation against the decimal forms of the IP address and inverted subnet mask.
      Get-BroadcastAddress expects both the IP address and subnet mask in dotted decimal format.
    .Parameter IPAddress
      Any IP address within the network range.
    .Parameter SubnetMask
      The subnet mask for the network.
  #&gt;

  [CmdLetBinding()]
  Param(
    [Parameter(Mandatory = $True, Position = 0, ValueFromPipeline = $True)]
    [Net.IPAddress]$IPAddress, 

    [Parameter(Mandatory = $True, Position = 1)]
    [Alias(&quot;Mask&quot;)]
    [Net.IPAddress]$SubnetMask
  )

  Process {
    Return ConvertTo-DottedDecimalIP $((ConvertTo-DecimalIP $IPAddress) -BOr `
      ((-BNot (ConvertTo-DecimalIP $SubnetMask)) -BAnd [UInt32]::MaxValue))
  }
}
</pre>
<h3>Get-NetworkSummary</h3>
<p>Putting the functions above to work, providing a summary of an IP address range.</p>
<pre class="brush: powershell; title: ; notranslate">
Function Get-NetworkSummary ( [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; title: ; notranslate">
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; title: ; notranslate">
# 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-NetworkSummary 229.168.1.1 255.255.248.0
Get-NetworkSummary 172.16.1.243 18
Get-NetworkSummary 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://yarpp.org'>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>9</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://yarpp.org'>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; title: ; notranslate">
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; title: ; notranslate">
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; title: ; notranslate">
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; title: ; notranslate">
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; title: ; notranslate">
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; title: ; notranslate">
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://yarpp.org'>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>10</slash:comments>
		</item>
	</channel>
</rss>

