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
To access them all you need to do is require the
1 2 3 4 5 6 7 8 9 10 11 12
require 'resolv' str = "220.127.116.11" 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 = "18.104.22.168" 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.