如何检查字符串中的值是否为IP地址

时间:2021-07-10 07:20:41

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?

我得到了客户端的IP地址。但是如果我想验证变量中的值是否真的是IP呢?我怎么做?

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??

那么IPv6 IP呢?

12 个解决方案

#1


32  

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.

您也可以使用Ruby的内置IPAddr类,但它不适合验证。

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.

当然,如果应用程序服务器或框架为您提供了IP地址,则根本没有理由进行验证。只需使用提供给您的信息,并优雅地处理任何异常。

#2


27  

Ruby has already the needed Regex in the standard library. Checkout resolv.

Ruby已经在标准库中使用了所需的Regex。结帐解析。

require "resolv"

"192.168.1.1"   =~ Resolv::IPv4::Regex ? true : false #=> true
"192.168.1.500" =~ Resolv::IPv4::Regex ? true : false #=> false

"ff02::1"    =~ Resolv::IPv6::Regex ? true : false #=> true
"ff02::1::1" =~ Resolv::IPv6::Regex ? true : false #=> false

If you like it the short way ...

如果你喜欢它的短途...

require "resolv"

!!("192.168.1.1"   =~ Resolv::IPv4::Regex) #=> true
!!("192.168.1.500" =~ Resolv::IPv4::Regex) #=> false

!!("ff02::1"    =~ Resolv::IPv6::Regex) #=> true
!!("ff02::1::1" =~ Resolv::IPv6::Regex) #=> false

Have fun!

玩的开心!

#3


13  

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.

我用它来快速检查,因为它使用内置库。支持ipv4和ipv6。它不是很严格,例如,它说“999.999.999.999”是有效的。如果您需要更高精度,请查看获奖答案。

#4


7  

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.

由于大多数答案都不涉及IPV6验证,我遇到了类似的问题。我使用Ruby Regex库解决了它,就像@wingfire提到的那样。

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

但我也使用了Regexp库来使用它的union方法,如下所述

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 !

希望这可以帮助别人!

#5


4  

All answers above asume IPv4... you must ask yourself how wise it is to limit you app to IPv4 by adding these kind of checks in this day of the net migrating to IPv6.

以上所有答案都假设为IPv4 ...您必须问自己,在迁移到IPv6的这一天,通过添加这些检查将应用程序限制为IPv4是多么明智。

If you ask me: Don't validate it at all. Instead just pass the string as-is to the network components that will be using the IP address and let them do the validation. Catch the exceptions they will throw when it is wrong and use that information to tell the user what happened. Don't re-invent the wheel, build upon the work of others.

如果你问我:根本不要验证它。相反,只需将字符串按原样传递给将使用IP地址的网络组件,然后让它们进行验证。捕获它们在出错时将抛出的异常,并使用该信息告诉用户发生了什么。不要重新发明*,建立在他人的工作基础之上。

#6


4  

Use http://www.ruby-doc.org/stdlib-1.9.3/libdoc/ipaddr/rdoc/IPAddr.html it performs validation for you. Just rescue the exception with false and you know that it was invalid.

使用http://www.ruby-doc.org/stdlib-1.9.3/libdoc/ipaddr/rdoc/IPAddr.html它会为您执行验证。只是用false来拯救异常并且你知道它是无效的。

1.9.3p194 :002 > IPAddr.new('1.2.3.4')
 => #<IPAddr: IPv4:1.2.3.4/255.255.255.255> 
1.9.3p194 :003 > IPAddr.new('1.2.3.a')
ArgumentError: invalid address
  from /usr/local/rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/ipaddr.rb:496:in `rescue in initialize'
  from /usr/local/rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/ipaddr.rb:493:in `initialize'
  from (irb):3:in `new'
  from (irb):3
  from /usr/local/rvm/rubies/ruby-1.9.3-p194/bin/irb:16:in `<main>'

#7


3  

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

#8


1  

Try this

尝试这个

Use IPAddr

使用IPAddr

require 'ipaddr'
true if IPAddr.new(ip) rescue false

#9


1  

This regular expression I use which I found here

我使用的这个正则表达式,我在这里找到

/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/

/ ^(?:( ?: 25 [0-5] | 2 [0-4] [0-9] |?[01] [0-9] [0-9])。\){3}( ?:?25 [0-5] | 2 [0-4] [0-9] | [01] [0-9] [0-9])$ /

#10


0  

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.

字符串形式的IP地址必须包含四个数字,以点分隔。每个数字必须介于0到255之间(包括0和255)。

#11


0  

Validate using regular expression:

使用正则表达式验证:

\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}

#12


0  

for match a valid IP adress with regexp use

匹配使用正则表达式的有效IP地址

^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$

instead of

代替

^([01]?[0-9][0-9]?|2[0-4][0-9]|25[0-5])(\.([01]?[0-9][0-9]?|2[0-4][0-9]|25[0-5])){3}$

because many regex engine match the first possibility in the OR sequence

因为许多正则表达式引擎匹配OR序列中的第一种可能性

you can try your regex engine : 10.48.0.200

你可以试试你的正则表达式引擎:10.48.0.200

test the difference here

在这里测试差异

#1


32  

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.

您也可以使用Ruby的内置IPAddr类,但它不适合验证。

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.

当然,如果应用程序服务器或框架为您提供了IP地址,则根本没有理由进行验证。只需使用提供给您的信息,并优雅地处理任何异常。

#2


27  

Ruby has already the needed Regex in the standard library. Checkout resolv.

Ruby已经在标准库中使用了所需的Regex。结帐解析。

require "resolv"

"192.168.1.1"   =~ Resolv::IPv4::Regex ? true : false #=> true
"192.168.1.500" =~ Resolv::IPv4::Regex ? true : false #=> false

"ff02::1"    =~ Resolv::IPv6::Regex ? true : false #=> true
"ff02::1::1" =~ Resolv::IPv6::Regex ? true : false #=> false

If you like it the short way ...

如果你喜欢它的短途...

require "resolv"

!!("192.168.1.1"   =~ Resolv::IPv4::Regex) #=> true
!!("192.168.1.500" =~ Resolv::IPv4::Regex) #=> false

!!("ff02::1"    =~ Resolv::IPv6::Regex) #=> true
!!("ff02::1::1" =~ Resolv::IPv6::Regex) #=> false

Have fun!

玩的开心!

#3


13  

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.

我用它来快速检查,因为它使用内置库。支持ipv4和ipv6。它不是很严格,例如,它说“999.999.999.999”是有效的。如果您需要更高精度,请查看获奖答案。

#4


7  

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.

由于大多数答案都不涉及IPV6验证,我遇到了类似的问题。我使用Ruby Regex库解决了它,就像@wingfire提到的那样。

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

但我也使用了Regexp库来使用它的union方法,如下所述

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 !

希望这可以帮助别人!

#5


4  

All answers above asume IPv4... you must ask yourself how wise it is to limit you app to IPv4 by adding these kind of checks in this day of the net migrating to IPv6.

以上所有答案都假设为IPv4 ...您必须问自己,在迁移到IPv6的这一天,通过添加这些检查将应用程序限制为IPv4是多么明智。

If you ask me: Don't validate it at all. Instead just pass the string as-is to the network components that will be using the IP address and let them do the validation. Catch the exceptions they will throw when it is wrong and use that information to tell the user what happened. Don't re-invent the wheel, build upon the work of others.

如果你问我:根本不要验证它。相反,只需将字符串按原样传递给将使用IP地址的网络组件,然后让它们进行验证。捕获它们在出错时将抛出的异常,并使用该信息告诉用户发生了什么。不要重新发明*,建立在他人的工作基础之上。

#6


4  

Use http://www.ruby-doc.org/stdlib-1.9.3/libdoc/ipaddr/rdoc/IPAddr.html it performs validation for you. Just rescue the exception with false and you know that it was invalid.

使用http://www.ruby-doc.org/stdlib-1.9.3/libdoc/ipaddr/rdoc/IPAddr.html它会为您执行验证。只是用false来拯救异常并且你知道它是无效的。

1.9.3p194 :002 > IPAddr.new('1.2.3.4')
 => #<IPAddr: IPv4:1.2.3.4/255.255.255.255> 
1.9.3p194 :003 > IPAddr.new('1.2.3.a')
ArgumentError: invalid address
  from /usr/local/rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/ipaddr.rb:496:in `rescue in initialize'
  from /usr/local/rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/ipaddr.rb:493:in `initialize'
  from (irb):3:in `new'
  from (irb):3
  from /usr/local/rvm/rubies/ruby-1.9.3-p194/bin/irb:16:in `<main>'

#7


3  

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

#8


1  

Try this

尝试这个

Use IPAddr

使用IPAddr

require 'ipaddr'
true if IPAddr.new(ip) rescue false

#9


1  

This regular expression I use which I found here

我使用的这个正则表达式,我在这里找到

/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/

/ ^(?:( ?: 25 [0-5] | 2 [0-4] [0-9] |?[01] [0-9] [0-9])。\){3}( ?:?25 [0-5] | 2 [0-4] [0-9] | [01] [0-9] [0-9])$ /

#10


0  

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.

字符串形式的IP地址必须包含四个数字,以点分隔。每个数字必须介于0到255之间(包括0和255)。

#11


0  

Validate using regular expression:

使用正则表达式验证:

\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}

#12


0  

for match a valid IP adress with regexp use

匹配使用正则表达式的有效IP地址

^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$

instead of

代替

^([01]?[0-9][0-9]?|2[0-4][0-9]|25[0-5])(\.([01]?[0-9][0-9]?|2[0-4][0-9]|25[0-5])){3}$

because many regex engine match the first possibility in the OR sequence

因为许多正则表达式引擎匹配OR序列中的第一种可能性

you can try your regex engine : 10.48.0.200

你可以试试你的正则表达式引擎:10.48.0.200

test the difference here

在这里测试差异