require 'resolv' str = "184.108.40.206" 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 = "220.127.116.11" valid = !(IPAddr.new(str) rescue nil).nil?
You can also use https://github.com/deploy2/ruby-ip gem for this.