2 Comments

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:

1
2
3
4
5
6
7
8
9
10
11
12
require 'resolv'
 
str = "108.168.213.2"
 
case str
when Resolv::IPv4::Regex
  puts "It's a valid IPv4 address."
when Resolv::IPv6::Regex
  puts "It's a valid IPv6 address."
else
  puts "It's not a valid IP address."
end

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:

1
2
3
4
5
require 'ipaddr'
 
str = "108.168.213.2"
 
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.