3

I want to verify whether a given string is valid IPv4 address or not in ruby. I tried as follows but what is does is matches values greater than 255 as well. How to limit each block's range from 0-255

str="255.255.255.256"
if str=~ /\b[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\b/
puts true
else
puts false
end
Aniket
  • 67
  • 1
  • 5
  • 1
    Or if you really want to stick with regexp solutions: http://stackoverflow.com/questions/106179/regular-expression-to-match-hostname-or-ip-address – samuil Apr 17 '14 at 06:34

4 Answers4

15

You have the IPAddr class in Ruby. You do not need to validate it agains a regex, just create a new object and catch the exception when it fails:

require 'ipaddr'

ip = IPAddr.new "127.0.0.1"
# => #<IPAddr: IPv4:127.0.0.1/255.255.255.255>

ip = IPAddr.new "127.0.0.a"
# => IPAddr::InvalidAddressError: invalid address
sawa
  • 165,429
  • 45
  • 277
  • 381
Paulo Fidalgo
  • 21,709
  • 7
  • 99
  • 115
  • 2
    Actually just catching this exception is not enough to ensure you have an IPv4 address, you also need to check `ip.ipv4?` returns `true`. Consider the example given in the docs: `IPAddr.new "3ffe:505:2::1"`. This does not raise an exception, as it is a valid IPv6 address. – MatzFan Dec 11 '17 at 13:27
9
block = /\d{,2}|1\d{2}|2[0-4]\d|25[0-5]/
re = /\A#{block}\.#{block}\.#{block}\.#{block}\z/

re =~ "255.255.255.255" # => 0
re =~ "255.255.255.256" # => nil
sawa
  • 165,429
  • 45
  • 277
  • 381
7

You'd better to use ruby core class IPAddress

you could do it this way:

 require "ipaddress"

 IPAddress.valid? "192.128.0.12"
 #=> true

 IPAddress.valid? "192.128.0.260"
 #=> false

you could find more here How do I check whether a value in a string is an IP address

Community
  • 1
  • 1
shemerey
  • 501
  • 2
  • 5
1

This is a way that reads pretty easily:

str.count('.')==3 && str.split('.').all? {|s| s[/^\d{3}$/] && s.to_i < 256}
Cary Swoveland
  • 106,649
  • 6
  • 63
  • 100