We're hiring!

We're actively seeking designers and developers for all three of our locations.

Using Regular Expressions to Validate an IP Address in Ruby

Did you know that the Ruby standard library includes regular expressions for validating both IPv4 and IPv6 addresses? I came across this fact while researching how to best go about validating a user-entered IP address in a Ruby application. This stackoverflow question pointed it out to me.

Via the Resolv Library

It turns out the Resolv standard library includes the Resolv::IPv4 class and the Resolv::IPv6 class, each of which expose a regular expression to validate their respective formats.

To access them all you need to do is require the resolv library:

require 'resolv'
str = ""
case str
when Resolv::IPv4::Regex
  puts "It's a valid IPv4 address."
when Resolv::IPv6::Regex
  puts "It's a valid IPv6 address."
  puts "It's not a valid IP address."

Via the ipaddr Library

In addition to using the Resolv regular expressions, there is also another way to validate an IP address string in Ruby’s standard library. The ipaddr library’s IPAddr class will raise an exception if you try to create an instance with an invalid address. For example:

require 'ipaddr'
str = ""
valid = !(IPAddr.new(str) rescue nil).nil?

Keep in mind that, according to the author of the ruby-ip gem:

IPAddr uses calls to the socket library to validate IP addresses, and this can trigger spurious DNS lookups when given an invalid IP address.


Patrick Bacon (48 Posts)

I’m a software developer at Atomic Object (since 2005) in Grand Rapids, MI.

This entry was posted in Ruby and tagged , . Bookmark the permalink. Both comments and trackbacks are currently closed.


  1. Lecky
    Posted August 30, 2013 at 1:18 am

    FYI: Rails4 with Postgres support an inet attribute which can automatic return IP address with IPAddr object.

  2. Posted November 11, 2013 at 12:00 am

    Thanks for unearthing this well-kept secret – I would have thought Resolv was only in Ruby 2.0, but I googled around and apparently it’s in 1.9 as well!