How do I check whether a value in a string is an IP address How do I check whether a value in a string is an IP address ruby ruby

How do I check whether a value in a string is an IP address


Ruby has already the needed Regex in the standard library.Checkout resolv.

require "resolv""192.168.1.1"   =~ Resolv::IPv4::Regex ? true : false #=> true"192.168.1.500" =~ Resolv::IPv4::Regex ? true : false #=> false"ff02::1"    =~ Resolv::IPv6::Regex ? true : false #=> true"ff02::1::1" =~ Resolv::IPv6::Regex ? true : false #=> false

If you like it the short way ...

require "resolv"!!("192.168.1.1"   =~ Resolv::IPv4::Regex) #=> true!!("192.168.1.500" =~ Resolv::IPv4::Regex) #=> false!!("ff02::1"    =~ Resolv::IPv6::Regex) #=> true!!("ff02::1::1" =~ Resolv::IPv6::Regex) #=> false

Have fun!

Update (2018-10-08):

From the comments below i love the very short version:

!!(ip_string =~ Regexp.union([Resolv::IPv4::Regex, Resolv::IPv6::Regex]))

Very elegant with rails (also an answer from below):

validates :ip,          :format => {            :with => Regexp.union(Resolv::IPv4::Regex, Resolv::IPv6::Regex)          }


Why not let a library validate it for you? You shouldn't introduce complex regular expressions that are impossible to maintain.

% gem install ipaddress

Then, in your application

require "ipaddress"IPAddress.valid? "192.128.0.12"#=> trueIPAddress.valid? "192.128.0.260"#=> false# Validate IPv6 addresses without additional work.IPAddress.valid? "ff02::1"#=> trueIPAddress.valid? "ff02::ff::1"#=> falseIPAddress.valid_ipv4? "192.128.0.12"#=> trueIPAddress.valid_ipv6? "192.128.0.12"#=> false

You can also use Ruby's built-in IPAddr class, but it doesn't lend itself very well for validation.

Of course, if the IP address is supplied to you by the application server or framework, there is no reason to validate at all. Simply use the information that is given to you, and handle any exceptions gracefully.


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

I use it for quick check because it uses built in library. Supports both ipv4 and ipv6. It is not very strict though, it says '999.999.999.999' is valid, for example. See the winning answer if you need more precision.