Method: IPAddress.parse

Defined in:
lib/ipaddress.rb

.parse(str) ⇒ Object

Parse the argument string to create a new IPv4, IPv6 or Mapped IP object

ip  = IPAddress.parse 167837953 # 10.1.1.1  
ip  = IPAddress.parse "172.16.10.1/24"
ip6 = IPAddress.parse "2001:db8::8:800:200c:417a/64"
ip_mapped = IPAddress.parse "::ffff:172.16.10.1/128"

All the object created will be instances of the correct class:

ip.class
  #=> IPAddress::IPv4
ip6.class
  #=> IPAddress::IPv6
ip_mapped.class
  #=> IPAddress::IPv6::Mapped


44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/ipaddress.rb', line 44

def IPAddress::parse(str)
  
  # Check if an int was passed
  if str.kind_of? Integer
    return IPAddress::IPv4.new(ntoa(str))  
  end

  case str
  when /:.+\./
    IPAddress::IPv6::Mapped.new(str)
  when /\./
    IPAddress::IPv4.new(str) 
  when /:/
    IPAddress::IPv6.new(str)
  else
    raise ArgumentError, "Unknown IP Address #{str}"
  end
end