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 = !( rescue nil).nil?

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

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


  • Lecky says:

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

  • Bruce says:

    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!

  • Comments are closed.