new(addr = '::', family = Socket::AF_UNSPEC)
public
Creates a new ipaddr object either
from a human readable IP address representation in string, or from a packed
in_addr value followed by an address
family.
In the former case, the following are the valid formats that will be
recognized: “address”, “address/prefixlen” and “address/mask”,
where IPv6 address may be enclosed in square brackets (`[‘ and `]’).
If a prefixlen or a mask is specified, it
returns a masked IP address. Although the address family is determined
automatically from a specified string, you can specify one explicitly by
the optional second argument.
Otherwise an IP address is generated from a packed in_addr value and an address family.
The IPAddr class defines many methods and
operators, and some of those, such as &, |, include? and ==, accept a string, or a
packed in_addr value instead of an IPAddr object.
Show source
def initialize(addr = '::', family = Socket::AF_UNSPEC)
if !addr.kind_of?(String)
case family
when Socket::AF_INET, Socket::AF_INET6
set(addr.to_i, family)
@mask_addr = (family == Socket::AF_INET) ? IN4MASK : IN6MASK
return
when Socket::AF_UNSPEC
raise AddressFamilyError, "address family must be specified"
else
raise AddressFamilyError, "unsupported address family: #{family}"
end
end
prefix, prefixlen = addr.split('/')
if prefix =~ /\A\[(.*)\]\z/
prefix = $1
family = Socket::AF_INET6
end
@addr = @family = nil
if family == Socket::AF_UNSPEC || family == Socket::AF_INET
@addr = in_addr(prefix)
if @addr
@family = Socket::AF_INET
end
end
if !@addr && (family == Socket::AF_UNSPEC || family == Socket::AF_INET6)
@addr = in6_addr(prefix)
@family = Socket::AF_INET6
end
if family != Socket::AF_UNSPEC && @family != family
raise AddressFamilyError, "address family mismatch"
end
if prefixlen
mask!(prefixlen)
else
@mask_addr = (@family == Socket::AF_INET) ? IN4MASK : IN6MASK
end
end