Welcome to MSDN Blogs Sign in | Join | Help

Regular Expressions and IP addresses (ipv4 and IPv6)

Over the last year or so I have been writing automation that uses IPv4 and IPv6 addresses.  In the beginning I had to dig up and make some regular expressions for verifying that a given value was a valid IPv4 or IPv6 address. 

The ones I came up with are (in VB.net)

Const strIPv4Pattern as string = "\A(25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}\z" 'IPv4 Address Regex pattern (x.x.x.x)

Const strIPv6Pattern as string = "\A(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}\z"

Const strIPv6Pattern_HEXCompressed as string = "\A((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)::((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)\z"

Const StrIPv6Pattern_6Hex4Dec as string = "\A((?:[0-9A-Fa-f]{1,4}:){6,6})(25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}\z"

Const StrIPv6Pattern_Hex4DecCompressed as string = "\A((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?) ::((?:[0-9A-Fa-f]{1,4}:)*)(25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}\z"

Now because an IPv6 address can take a few forms we have 4 different expressions for IPv6.  If someone finds a bug in one of these please let me know.  Because RegExp is something that I am not good at. 

Hope these will help some one.

Published Monday, January 10, 2005 9:37 AM by mpoulson
Filed under: , ,

Comments

Monday, January 10, 2005 3:45 PM by Brent Holliman (aka dirtyb)

# Checking for IP's using Regex?

Tuesday, January 25, 2005 4:56 PM by leokapil

# re: Regular Expressions and IP addresses (ipv4 and IPv6)

Hi there, I have to convert the following java regex to .Net regex, this one does not seem to be working in .Net.

<RegexPattern pattern="^150\.215\.([12]\d{2}|[13-9]\d|2[2-9]|[1-9])\.\d{1,3}$" />


Please email me at leokapil2000@hotmail.com

Thanks,
leo

# Actors and Actresses &raquo; Archive du blog &raquo; Mike Poulson&#8217;s Thoughts on lots of stuff : Regular Expressions and IP &#8230;

# Actors and Actresses &raquo; Mike Poulson&#8217;s Thoughts on lots of stuff : Regular Expressions and IP &#8230;

# Dinner and a Movie &raquo; Mike Poulson&#8217;s Thoughts on lots of stuff : Regular Expressions and IP &#8230;

New Comments to this post are disabled
 
Page view tracker