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

发布于 2024-09-17 08:45:38 字数 224 浏览 7 评论 0原文

当我这样做时,

ip = request.env["REMOTE_ADDR"]

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

请帮忙。 提前致谢。抱歉,如果这个问题重复出现,我没有花力气找到它...

编辑

IPv6 IP 怎么样?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(13

仅冇旳回忆 2024-09-24 08:45:38

Ruby 已经在标准库中提供了所需的正则表达式。
查看resolv

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

如果您喜欢简短的方式...

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

玩得开心!

更新

根据下面的评论,我喜欢用于检查 IPv4 或 IPv6 的非常简短的版本:

!!(ip_string =~ Resolv::AddressRegex)

非常优雅的 Rails(也是下面的答案):

validates :ip,
          :format => {
            :with => Resolv::AddressRegex
          }

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

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!

Update:

From the comments below I love the very short version for checking for IPv4 or IPv6:

!!(ip_string =~ Resolv::AddressRegex)

Very elegant with Rails (also an answer from below):

validates :ip,
          :format => {
            :with => Resolv::AddressRegex
          }
帅的被狗咬 2024-09-24 08:45:38

为什么不让为您验证它呢?您不应该引入无法维护的复杂正则表达式。

% gem install ipaddress

然后,在您的应用程序中

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

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

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

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.

送君千里 2024-09-24 08:45:38
require 'ipaddr'
!(IPAddr.new(str) rescue nil).nil?

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

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.

时光瘦了 2024-09-24 08:45:38

由于大多数答案都没有谈到 IPV6 验证,因此我遇到了类似的问题。
我通过使用 Ruby Regex 库解决了这个问题,正如 @wingfire 提到的那样。

但我也使用正则表达式库来使用它的 union 方法,如所解释的 这里

我有这个验证代码:

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

希望这可以帮助别人!

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 !

把梦留给海 2024-09-24 08:45:38

使用 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>'

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.

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>'
瞎闹 2024-09-24 08:45:38
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

或者,如果您不介意扩展核心类:

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
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
暮色兮凉城 2024-09-24 08:45:38

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

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

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.

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.

静谧 2024-09-24 08:45:38

尝试

使用 IPAddr< /a>

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

Try this

Use IPAddr

require 'ipaddr'
true if IPAddr.new(ip) rescue false
背叛残局 2024-09-24 08:45:38

我使用的这个正则表达式是我在此处

/^(?:( ?: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]?)$/

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]?)$/

一身仙ぐ女味 2024-09-24 08:45:38

字符串形式的 IP 地址必须恰好包含四个数字,并用点分隔。每个数字必须在 0 到 255 之间(含 0 和 255)。

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.

海螺姑娘 2024-09-24 08:45:38

使用正则表达式验证:

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

Validate using regular expression:

\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}
情绪操控生活 2024-09-24 08:45:38

为了使用正则表达式匹配有效的 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}$

而不是

^([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}$

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

,您可以尝试您的正则表达式引擎:10.48.0.200

测试差异 这里

for match a valid IP adress with regexp use

^(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

you can try your regex engine : 10.48.0.200

test the difference here

筑梦 2024-09-24 08:45:38

对于ipv4

def ipv4?(str)
   nums = str.split('.')
   reg = /^\d$|^[1-9]\d$|^1\d\d$|^2[0-4]\d$|^25[0-5]$/
   nums.length == 4 && (nums.count {|n| reg.match?(n)}) == 4
end

for ipv4

def ipv4?(str)
   nums = str.split('.')
   reg = /^\d$|^[1-9]\d$|^1\d\d$|^2[0-4]\d$|^25[0-5]$/
   nums.length == 4 && (nums.count {|n| reg.match?(n)}) == 4
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文