我想使用Resolv库解析包括“localhost”在内的主机名,但它也列出了非ipv4地址。我想找出第一个IPv4地址看了图书馆,但找不到办法有人知道如何做到这一点,还是我们应该去其他宝石,如网络:域名系统或dnsruby?

最佳答案

如果我理解正确,您可以使用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.

10-08 14:27