How do I check whether a value in a string is an I

2019-01-31 19:14发布

when I do this

ip = request.env["REMOTE_ADDR"]

I get the client's IP address it it. But what if I want to validate whether the value in the variable is really an IP? How do I do that?

Please help. Thanks in advance. And sorry if this question is repeated, I didn't take the effort of finding it...

EDIT

What about IPv6 IP's??

12条回答
叼着烟拽天下
2楼-- · 2019-01-31 19:32
require 'ipaddr'
!(IPAddr.new(str) rescue nil).nil?

I use it for quick check because it uses built in library. Supports both ipv4 and ipv6. It is not very strict though, it says '999.999.999.999' is valid, for example. See the winning answer if you need more precision.

查看更多
神经病院院长
3楼-- · 2019-01-31 19:34
require 'ipaddr'

def is_ip?(ip)
  !!IPAddr.new(ip) rescue false
end

is_ip?("192.168.0.1")
=> true

is_ip?("www.google.com")
=> false

Or, if you don't mind extending core classes:

require 'ipaddr'

class String
  def is_ip?
    !!IPAddr.new(self) rescue false
  end
end

"192.168.0.1".is_ip?
=> true

"192.168.0.512".is_ip?
=> false
查看更多
Juvenile、少年°
4楼-- · 2019-01-31 19:35

Why not let a library validate it for you? You shouldn't introduce complex regular expressions that are impossible to maintain.

% gem install ipaddress

Then, in your application

require "ipaddress"

IPAddress.valid? "192.128.0.12"
#=> true

IPAddress.valid? "192.128.0.260"
#=> false

# Validate IPv6 addresses without additional work.
IPAddress.valid? "ff02::1"
#=> true

IPAddress.valid? "ff02::ff::1"
#=> false


IPAddress.valid_ipv4? "192.128.0.12"
#=> true

IPAddress.valid_ipv6? "192.128.0.12"
#=> false

You can also use Ruby's built-in IPAddr class, but it doesn't lend itself very well for validation.

Of course, if the IP address is supplied to you by the application server or framework, there is no reason to validate at all. Simply use the information that is given to you, and handle any exceptions gracefully.

查看更多
冷血范
5楼-- · 2019-01-31 19:40

IP address in a string form must contain exactly four numbers, separated by dots. Each number must be in a range between 0 and 255, inclusive.

查看更多
老娘就宠你
6楼-- · 2019-01-31 19:42

As most of the answers don't speak about IPV6 validation, I had the similar problem. I solved it by using the Ruby Regex Library, as @wingfire mentionned it.

But I also used the Regexp Library to use it's union method as explained here

I so have this code for a validation :

validates :ip, :format => { 
                  :with => Regexp.union(Resolv::IPv4::Regex, Resolv::IPv6::Regex)
                }

Hope this can help someone !

查看更多
爷的心禁止访问
7楼-- · 2019-01-31 19:42

Validate using regular expression:

\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}
查看更多
登录 后发表回答