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
You just need to use ‘resolv’ lib.
Here is one more method but it throughs exception in case of invalid Ip.
require 'ipaddr' str = "188.8.131.52" valid = !(IPAddr.new(str) rescue nil).nil?
You can also use https://github.com/deploy2/ruby-ip gem for this.