# ipaddr.rb - A class to manipulate an IP address
# Copyright (c) 2002 Hajimu UMEMOTO <ume@mahoroba.org>.
# Copyright (c) 2007, 2009, 2012 Akinori MUSHA <knu@iDaemons.org>.
# You can redistribute and/or modify it under the same terms as Ruby.
# $Id: ipaddr.rb 52741 2015-11-24 15:49:21Z nagachika $
# - Akinori MUSHA <knu@iDaemons.org> (current maintainer)
# IPAddr provides a set of methods to manipulate an IP address. Both IPv4 and
# ipaddr1 = IPAddr.new "3ffe:505:2::1"
# p ipaddr1 #=> #<IPAddr: IPv6:3ffe:0505:0002:0000:0000:0000:0000:0001/ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff>
# p ipaddr1.to_s #=> "3ffe:505:2::1"
# ipaddr2 = ipaddr1.mask(48) #=> #<IPAddr: IPv6:3ffe:0505:0002:0000:0000:0000:0000:0000/ffff:ffff:ffff:0000:0000:0000:0000:0000>
# p ipaddr2.to_s #=> "3ffe:505:2::"
# ipaddr3 = IPAddr.new "192.168.2.0/24"
# p ipaddr3 #=> #<IPAddr: IPv4:192.168.2.0/255.255.255.0>
IN6MASK = 0xffffffffffffffffffffffffffffffff
IN6FORMAT = (["%.4x"] * 8).join(':')
# Regexp _internally_ used for parsing IPv4 address.
(\d+) \. (\d+) \. (\d+) \. (\d+)
# Regexp _internally_ used for parsing IPv6 address.
RE_IPV6ADDRLIKE_FULL = %r{
(?: [\da-f]{1,4} : ){7} [\da-f]{1,4}
( (?: [\da-f]{1,4} : ){6} )
(\d+) \. (\d+) \. (\d+) \. (\d+)
# Regexp _internally_ used for parsing IPv6 address.
RE_IPV6ADDRLIKE_COMPRESSED = %r{
( (?: (?: [\da-f]{1,4} : )* [\da-f]{1,4} )? )
( (?: [\da-f]{1,4} : )* )
(\d+) \. (\d+) \. (\d+) \. (\d+)
# Generic IPAddr related error. Exceptions raised in this class should
class Error < ArgumentError; end
# Raised when the provided IP address is an invalid address.
class InvalidAddressError < Error; end
# Raised when the address family is invalid such as an address with an
# unsupported family, an address with an inconsistent family, or an address
# who's family cannot be determined.
class AddressFamilyError < Error; end
# Raised when the address is an invalid length.
class InvalidPrefixError < InvalidAddressError; end
# Returns the address family of this IP address.
# Creates a new ipaddr containing the given network byte ordered
# string form of an IP address.
def IPAddr::new_ntoh(addr)
return IPAddr.new(IPAddr::ntop(addr))
# Convert a network byte ordered string form of an IP address into
s = addr.unpack('C4').join('.')
s = IN6FORMAT % addr.unpack('n8')
raise AddressFamilyError, "unsupported address family"
# Returns a new ipaddr built by bitwise AND.
return self.clone.set(@addr & coerce_other(other).to_i)
# Returns a new ipaddr built by bitwise OR.
return self.clone.set(@addr | coerce_other(other).to_i)
# Returns a new ipaddr built by bitwise right-shift.
return self.clone.set(@addr >> num)
# Returns a new ipaddr built by bitwise left shift.
return self.clone.set(addr_mask(@addr << num))
# Returns a new ipaddr built by bitwise negation.
return self.clone.set(addr_mask(~@addr))
# Returns true if two ipaddrs are equal.
other = coerce_other(other)
return @family == other.family && @addr == other.to_i
# Returns a new ipaddr built by masking IP address with the given
# prefixlen/netmask. (e.g. 8, 64, "255.255.255.0", etc.)
return self.clone.mask!(prefixlen)
# Returns true if the given ipaddr is in the range.
# net1 = IPAddr.new("192.168.2.0/24")
# net2 = IPAddr.new("192.168.2.100")
# net3 = IPAddr.new("192.168.3.0")
# p net1.include?(net2) #=> true
# p net1.include?(net3) #=> false
other = coerce_other(other)
if (@mask_addr >> 32) != 0xffffffffffffffffffffffff
mask_addr = (@mask_addr & IN4MASK)
other_addr = (other.to_i & IN4MASK)
other_family = Socket::AF_INET
other_family = other.family
if family != other_family
return ((addr & mask_addr) == (other_addr & mask_addr))
# Returns the integer representation of the ipaddr.
# Returns a string containing the IP address representation.
str.gsub!(/\b0{1,3}([\da-f]+)\b/i, '\1')
break if str.sub!(/\A0:0:0:0:0:0:0:0\z/, '::')
break if str.sub!(/\b0:0:0:0:0:0:0\b/, ':')
break if str.sub!(/\b0:0:0:0:0:0\b/, ':')
break if str.sub!(/\b0:0:0:0:0\b/, ':')
break if str.sub!(/\b0:0:0:0\b/, ':')
break if str.sub!(/\b0:0:0\b/, ':')
break if str.sub!(/\b0:0\b/, ':')
if /\A::(ffff:)?([\da-f]{1,4}):([\da-f]{1,4})\z/i =~ str
str = sprintf('::%s%d.%d.%d.%d', $1, $2.hex / 256, $2.hex % 256, $3.hex / 256, $3.hex % 256)
# Returns a string containing the IP address representation in
# Returns a network byte ordered string form of the IP address.
(@addr >> (112 - 16 * i)) & 0xffff
raise AddressFamilyError, "unsupported address family"
# Returns true if the ipaddr is an IPv4 address.
return @family == Socket::AF_INET
# Returns true if the ipaddr is an IPv6 address.
return @family == Socket::AF_INET6
# Returns true if the ipaddr is an IPv4-mapped IPv6 address.
return ipv6? && (@addr >> 32) == 0xffff
# Returns true if the ipaddr is an IPv4-compatible IPv6 address.
if !ipv6? || (@addr >> 32) != 0
# Returns a new ipaddr built by converting the native IPv4 address
# into an IPv4-mapped IPv6 address.
raise InvalidAddressError, "not an IPv4 address"
return self.clone.set(@addr | 0xffff00000000, Socket::AF_INET6)
# Returns a new ipaddr built by converting the native IPv4 address
# into an IPv4-compatible IPv6 address.
raise InvalidAddressError, "not an IPv4 address"
return self.clone.set(@addr, Socket::AF_INET6)
# Returns a new ipaddr built by converting the IPv6 address into a
# native IPv4 address. If the IP address is not an IPv4-mapped or
# IPv4-compatible IPv6 address, returns self.
if !ipv4_mapped? && !ipv4_compat?
return self.clone.set(@addr & IN4MASK, Socket::AF_INET)
# Returns a string for DNS reverse lookup. It returns a string in
# RFC3172 form for an IPv6 address.
return _reverse + ".in-addr.arpa"
raise AddressFamilyError, "unsupported address family"
# Returns a string for DNS reverse lookup compatible with RFC3172.
raise InvalidAddressError, "not an IPv6 address"
return _reverse + ".ip6.arpa"
# Returns a string for DNS reverse lookup compatible with RFC1886.
raise InvalidAddressError, "not an IPv6 address"
return _reverse + ".ip6.int"
# Returns the successor to the ipaddr.
return self.clone.set(@addr + 1, @family)
# Compares the ipaddr with another.
other = coerce_other(other)
return nil if other.family != @family
return @addr <=> other.to_i
# Checks equality used by Hash.
return self.class == other.class && self.hash == other.hash && self == other
# Returns a hash value used by Hash, Set, and Array classes
return ([@addr, @mask_addr].hash << 1) | (ipv4? ? 0 : 1)
# Creates a Range object for the network address.
begin_addr = (@addr & @mask_addr)
end_addr = (@addr | (IN4MASK ^ @mask_addr))
end_addr = (@addr | (IN6MASK ^ @mask_addr))
raise AddressFamilyError, "unsupported address family"
return clone.set(begin_addr, @family)..clone.set(end_addr, @family)
# Returns a string containing a human-readable representation of the
# ipaddr. ("#<IPAddr: family:address/mask>")
raise AddressFamilyError, "unsupported address family"
return sprintf("#<%s: %s:%s/%s>", self.class.name,
af, _to_string(@addr), _to_string(@mask_addr))
# Set +@addr+, the internal stored ip address, to given +addr+. The
# parameter +addr+ is validated using the first +family+ member,
# which is +Socket::AF_INET+ or +Socket::AF_INET6+.
case family[0] ? family[0] : @family
if addr < 0 || addr > IN4MASK
raise InvalidAddressError, "invalid address"
if addr < 0 || addr > IN6MASK
raise InvalidAddressError, "invalid address"
raise AddressFamilyError, "unsupported address family"
# Set current netmask to given mask.
raise InvalidPrefixError, "address family is not same"
if prefixlen < 0 || prefixlen > 32
raise InvalidPrefixError, "invalid length"
@mask_addr = ((IN4MASK >> masklen) << masklen)
if prefixlen < 0 || prefixlen > 128
raise InvalidPrefixError, "invalid length"
masklen = 128 - prefixlen
@mask_addr = ((IN6MASK >> masklen) << masklen)
raise AddressFamilyError, "unsupported address family"
@addr = ((@addr >> masklen) << masklen)
# 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
# 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.
def initialize(addr = '::', family = Socket::AF_UNSPEC)
if !addr.kind_of?(String)
when Socket::AF_INET, Socket::AF_INET6
@mask_addr = (family == Socket::AF_INET) ? IN4MASK : IN6MASK
raise AddressFamilyError, "address family must be specified"
raise AddressFamilyError, "unsupported address family: #{family}"
prefix, prefixlen = addr.split('/')
if prefix =~ /\A\[(.*)\]\z/i
family = Socket::AF_INET6
# It seems AI_NUMERICHOST doesn't do the job.
#Socket.getaddrinfo(left, nil, Socket::AF_INET6, Socket::SOCK_STREAM, nil,
# Socket::AI_NUMERICHOST)
if family == Socket::AF_UNSPEC || family == Socket::AF_INET
@family = Socket::AF_INET
if !@addr && (family == Socket::AF_UNSPEC || family == Socket::AF_INET6)
@family = Socket::AF_INET6
if family != Socket::AF_UNSPEC && @family != family
raise AddressFamilyError, "address family mismatch"