[NoBrainer] Convert IP address string into an [IPAddress] compatible constructor string

When you try to convert an ip address string into an [IPAddress] object you might end up with a different address than expected. This can happen if you use the ‘leading zero’ notation for IPv4 addresse (which is not really correct, but easier to sort alphabetically). When you create an [IPAddress] with that kind address style, the constructor does internally some kind of type conversion and treats the leading zero as a hint to the ‘octal numbering system’. Therefore you end up with ‘8.1.4.10’ instead of ‘10.1.4.12’. Below you see a simple way to correct this via RegEx and Casting.

PS > $IpAddress = '010.001.004.012';
PS > [ipaddress] $ip = $IpAddress;
PS > $ip
Address            : 168034568
AddressFamily      : InterNetwork
ScopeId            :
IsIPv6Multicast    : False
IsIPv6LinkLocal    : False
IsIPv6SiteLocal    : False
IsIPv6Teredo       : False
IsIPv4MappedToIPv6 : False
IPAddressToString  : 8.1.4.10

PS > $IpAddress -match '^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$';
True
PS > $Matches
Name Value
---- -----
4    012
3    004
2    001
1    010
0    010.001.004.012

PS > $IpAddressShort = '{0}.{1}.{2}.{3}' -f
  ($Matches[1] -as [int]), ($Matches[2] -as [int]),
  ($Matches[3] -as [int]), ($Matches[4] -as [int]);
PS > $IpAddressShort
10.1.4.12
PS > [ipaddress] $ip = $IpAddressShort;
PS > $ip
Address            : 201589002
AddressFamily      : InterNetwork
ScopeId            :
IsIPv6Multicast    : False
IsIPv6LinkLocal    : False
IsIPv6SiteLocal    : False
IsIPv6Teredo       : False
IsIPv4MappedToIPv6 : False
IPAddressToString  : 10.1.4.12

Note: there is no need to have a more precise regex in place, as the constructor would fail any non-valid input anyway.

Trackbacks

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

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: