简体   繁体   中英

IP address format check

I am developing a Ruby on Rails application by using Ruby v1.8.7 . My question is more about Ruby language.

I know there is a build-in Ruby library named IPAddr in Ruby v1.8.7 . It handles IP address related issues well. But, seems it does not provide any method to check IP address format.

Could someone provide me a good way to check IP address format (IPv4 and IPv6 addresses) in Ruby? Thank you.

PS

I tried a regular expression way:

ip_regex = ^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.
([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])$

ip_addr='127.0.0.3'
ip_addr =~ ip_regex

But it does not work...

http://www.ruby-doc.org/stdlib-1.8.7/libdoc/ipaddr/rdoc/IPAddr.html

The IPAddr class already provides methods to check whether they're IPV4 or IPV6 formats:

  • #ipv4?
  • #ipv6?

ActiveValidators has an IP validator.
It uses a regex for any ipv4, and Resolv::IPv6::Regex for any ipv6 address.

To use it, it's very simple.
Add activevalidators to your Gemfile.

gem 'activevalidators'

Then, in your Computer class :

class Computer << ActiveRecord::Base
  validates :remote_address,
    :ip => { :format => :v4 }
end

Looks like your regular expression is wrong. It should be:

/^([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])$/
validates :ip,
      :format => {
        :with => Regexp.union(Resolv::IPv4::Regex, Resolv::IPv6::Regex)
      }

From https://stackoverflow.com/a/15157862/378006

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM