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