Returns a String
based representation of a valid DNS hostname,
IPv4 or IPv6 address.
IPSocket.getaddress 'localhost' #=> "::1" IPSocket.getaddress 'broadcasthost' #=> "255.255.255.255" IPSocket.getaddress 'www.ruby-lang.org' #=> "221.186.184.68" IPSocket.getaddress 'www.ccc.de' #=> "2a00:1328:e102:ccc0::122"
# File ipaddr.rb, line 63 def getaddress(s) if valid?(s) s elsif %r\A[-A-Za-z\d.]+\Z/ =~ s getaddress_orig(s) else raise ArgumentError, "invalid address" end end
Returns true
if addr
is either a valid IPv4 or
IPv6 address.
# File ipaddr.rb, line 50 def valid?(addr) valid_v4?(addr) || valid_v6?(addr) end
Returns true
if addr
is a valid IPv4 address.
# File ipaddr.rb, line 28 def valid_v4?(addr) if %r\A(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\Z/ =~ addr return $~.captures.all? {|i| i.to_i < 256} end return false end
Returns true
if addr
is a valid IPv6 address.
# File ipaddr.rb, line 36 def valid_v6?(addr) # IPv6 (normal) return true if %r\A[\dA-Fa-f]{1,4}(:[\dA-Fa-f]{1,4})*\Z/ =~ addr return true if %r\A[\dA-Fa-f]{1,4}(:[\dA-Fa-f]{1,4})*::([\dA-Fa-f]{1,4}(:[\dA-Fa-f]{1,4})*)?\Z/ =~ addr return true if %r\A::([\dA-Fa-f]{1,4}(:[\dA-Fa-f]{1,4})*)?\Z/ =~ addr # IPv6 (IPv4 compat) return true if %r\A[\dA-Fa-f]{1,4}(:[\dA-Fa-f]{1,4})*:/ =~ addr && valid_v4?($') return true if %r\A[\dA-Fa-f]{1,4}(:[\dA-Fa-f]{1,4})*::([\dA-Fa-f]{1,4}(:[\dA-Fa-f]{1,4})*:)?/ =~ addr && valid_v4?($') return true if %r\A::([\dA-Fa-f]{1,4}(:[\dA-Fa-f]{1,4})*:)?/ =~ addr && valid_v4?($') false end
Commenting is here to help enhance the documentation. For example, sample code, or clarification of the documentation.
If you have questions about Ruby or the documentation, please post to one of the Ruby mailing lists. You will get better, faster, help that way.
If you wish to post a correction of the docs, please do so, but also file bug report so that it can be corrected for the next release. Thank you.