[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

  2. Ralph says:

    I am interested int this…. however, I am a powershell noobie. How do you run this? And do you run it against a file? If so, what format does the IP addressing need to be in?

    • Ronald Rink says:

      `Convert-IpAddressToMaskLength` is a PowerShell function, which you can run directly from the console once you have defined it. Defining the function can be either done by simply pasting it into the console or by “dot-sourcing” it from a file. The format of the IP address would be “dotted”, e.g. 255.254.0.0 (like written in the blog post). If you want to convert multiple IP addresses you can put them into a file (one by a line) and then read them with `Get-Content` and pipe them to the method like this: `Get-Content myAddresses.txt | % { Convert-IpAddressToMaskLength $_ }`. For details on “dot-sourcing” etc have a look at StackOverflow.com or similar QA sites.

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: