1

我想使用Resolv库来解析包括“localhost”在内的主机名,但它也列出了非 IPv4 地址。我想找出第一个 IPv4 地址。看了看图书馆,但找不到这样做的方法。有谁知道这样做的方法,或者我们应该去寻找其他宝石,如 Net:DNS 或 dnsruby?

4

1 回答 1

3

如果我理解正确,您可以使用Resolv::IPv4::RegexpResolv::IPv6::Regexp查看示例:

=> require 'resolv'
=> p Resolv.getaddress "www.ruby-lang.org"
#> "23.23.144.121"
=> ip = "23.23.144.121"
=> ip =~ Resolv::IPv4::Regex
#> 0
=> ip =~ Resolv::IPv6::Regex
#> nil
=> case ip
=> when Resolv::IPv4::Regex
=> puts "It's a valid IPv4 address."
=> when Resolv::IPv6::Regex
=> puts "It's a valid IPv6 address."
=> else
=> puts "It's not a valid IP address."
=> end
#> It's a valid IPv4 address.
于 2014-07-25T10:11:09.220 回答