# frozen_string_literal: false
# 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 61155 2017-12-12 11:56:25Z shyouhei $
# - 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)
@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 a loopback address.
@addr & 0xff000000 == 0x7f000000
raise AddressFamilyError, "unsupported address family"
# Returns true if the ipaddr is a private address. IPv4 addresses
# in 10.0.0.0/8, 172.16.0.0/12 and 192.168.0.0/16 as defined in RFC
# 1918 and IPv6 Unique Local Addresses in fc00::/7 as defined in RFC
# 4193 are considered private.
@addr & 0xff000000 == 0x0a000000 || # 10.0.0.0/8
@addr & 0xfff00000 == 0xac100000 || # 172.16.0.0/12
@addr & 0xffff0000 == 0xc0a80000 # 192.168.0.0/16
@addr & 0xfe00_0000_0000_0000_0000_0000_0000_0000 == 0xfc00_0000_0000_0000_0000_0000_0000_0000
raise AddressFamilyError, "unsupported address family"
# Returns true if the ipaddr is a link-local address. IPv4
# addresses in 169.254.0.0/16 reserved by RFC 3927 and Link-Local
# IPv6 Unicast Addresses in fe80::/10 reserved by RFC 4291 are
@addr & 0xffff0000 == 0xa9fe0000 # 169.254.0.0/16
@addr & 0xffc0_0000_0000_0000_0000_0000_0000_0000 == 0xfe80_0000_0000_0000_0000_0000_0000_0000
raise AddressFamilyError, "unsupported address family"
# 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.
warn "IPAddr\##{__callee__} is obsolete", uplevel: 1 if $VERBOSE
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.
warn "IPAddr\##{__callee__} is obsolete", uplevel: 1 if $VERBOSE
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)
@addr <=> other.to_i if other.family == @family
# 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 the prefix length in bits for the ipaddr.
raise AddressFamilyError, "unsupported address family"
# Sets the prefix length in bits
raise InvalidPrefixError, "prefix must be an integer"
# 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.