[NoBrainer] Using PowerShell to convert an IPv4 subnet mask length into a subnet mask address

With PowerShell 3.0 and onwward you can easily convert a SubnetMask in bit form to a “real” dotted 4 octet format:

PS > $MaskLength = 24;
PS > [IPAddress] $ip = 0;
PS > $ip.Address = ([UInt32]::MaxValue -1) -shl (32 - $MaskLength) -shr (32 - $MaskLength)
PS > $ip

Address            : 16777215
AddressFamily      : InterNetwork
ScopeId            :
IsIPv6Multicast    : False
IsIPv6LinkLocal    : False
IsIPv6SiteLocal    : False
IsIPv6Teredo       : False
IsIPv4MappedToIPv6 : False
IPAddressToString  : 255.255.255.0

Reverting that operation is a bit trickier, but easily handable as well:

function Convert-IpAddressToMaskLength([string] $dottedIpAddressString)
{
  $result = 0; 
  # ensure we have a valid IP address
  [IPAddress] $ip = $dottedIpAddressString;
  $octets = $ip.IPAddressToString.Split('.');
  foreach($octet in $octets)
  {
    while(0 -ne $octet) 
    {
      $octet = ($octet -shl 1) -band [byte]::MaxValue
      $result++; 
    }
  }
  return $result;
}

PS > Convert-IpAddressToMaskLength 255.254.0.0
15
PS > Convert-IpAddressToMaskLength 255.255.128.0
17

UPDATE: be careful when trying to convert IP addresses with leading zeros, as described in this post.

Comments

  1. Fyi, revert doesn’t seem to work with anything other than 255. Nice logic though.

    • Ronald Rink says:

      Hi Christopher, thanks for your hint – very much appreciated! I corrected the error and it seems to be working correctly now.
      Regards, Ronald

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: