Regular Expression to validate an IP


Check valid IP address or not

Precious Info

require 'resolv'
 
str = "108.168.213.2"
 
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 = "108.168.213.2"
 
valid = !(IPAddr.new(str) rescue nil).nil?

You can also use https://github.com/deploy2/ruby-ip gem for this.

View original post

Advertisements

I am Senior Software Engineer. I love reading, writing, sharing,developing, hiking, movies, trips, mountains, brooks, hills etc.

Posted in Uncategorized

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

StackOverFlow
Categories
Archives
%d bloggers like this: