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”:http://stackoverflow.com/questions/3756184/rails-3-validate-ip-string pointed it out to me.
Via the Resolv Library
It turns out the “Resolv”:http://www.ruby-doc.org/stdlib-2.0/libdoc/resolv/rdoc/ standard library includes the “Resolv::IPv4”:http://www.ruby-doc.org/stdlib-2.0/libdoc/resolv/rdoc/Resolv/IPv4.html class and the “Resolv::IPv6”:http://www.ruby-doc.org/stdlib-2.0/libdoc/resolv/rdoc/Resolv/IPv6.html 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 = "126.96.36.199" 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”:http://www.ruby-doc.org/stdlib-2.0/libdoc/ipaddr/rdoc/IPAddr.html library’s @IPAddr@ class will raise an exception if you try to create an instance with an invalid address. For example:
require 'ipaddr' str = "188.8.131.52" valid = !(IPAddr.new(str) rescue nil).nil?
Keep in mind that, according to the author of the “ruby-ip”:https://github.com/deploy2/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.