# ipaddr.rb - A class to manipulate an IP address
# Copyright (c) 2002 Hajimu UMEMOTO <ume@mahoroba.org>.
# Copyright (c) 2007 Akinori MUSHA <knu@iDaemons.org>.
# You can redistribute and/or modify it under the same terms as Ruby.
# $Id: ipaddr.rb 18049 2008-07-12 15:08:29Z shyouhei $
# - Akinori MUSHA <knu@iDaemons.org> (current maintainer)
unless Socket.const_defined? "AF_INET6"
if /\A(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\Z/ =~ addr
return $~.captures.all? {|i| i.to_i < 256}
return true if /\A[\dA-Fa-f]{1,4}(:[\dA-Fa-f]{1,4})*\Z/ =~ addr
return true if /\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 /\A::([\dA-Fa-f]{1,4}(:[\dA-Fa-f]{1,4})*)?\Z/ =~ addr
return true if /\A[\dA-Fa-f]{1,4}(:[\dA-Fa-f]{1,4})*:/ =~ addr && valid_v4?($')
return true if /\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 /\A::([\dA-Fa-f]{1,4}(:[\dA-Fa-f]{1,4})*:)?/ =~ addr && valid_v4?($')
valid_v4?(addr) || valid_v6?(addr)
alias getaddress_orig getaddress
elsif /\A[-A-Za-z\d.]+\Z/ =~ s
raise ArgumentError, "invalid address"
# 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(':')
# 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 ArgumentError, "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 "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 ArgumentError, "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 ArgumentError, "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 "unsupported address family"
# Returns a string for DNS reverse lookup compatible with RFC3172.
raise ArgumentError, "not an IPv6 address"
return _reverse + ".ip6.arpa"
# Returns a string for DNS reverse lookup compatible with RFC1886.
raise ArgumentError, "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
# 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 "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 "unsupported address family"
return sprintf("#<%s: %s:%s/%s>", self.class.name,
af, _to_string(@addr), _to_string(@mask_addr))
case family[0] ? family[0] : @family
if addr < 0 || addr > IN4MASK
raise ArgumentError, "invalid address"
if addr < 0 || addr > IN6MASK
raise ArgumentError, "invalid address"
raise ArgumentError, "unsupported address family"
raise ArgumentError, "address family is not same"
if prefixlen < 0 || prefixlen > 32
raise ArgumentError, "invalid length"
@mask_addr = ((IN4MASK >> masklen) << masklen)
if prefixlen < 0 || prefixlen > 128
raise ArgumentError, "invalid length"
masklen = 128 - prefixlen
@mask_addr = ((IN6MASK >> masklen) << masklen)
raise "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 addess 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 ArgumentError, "address family must be specified"
raise ArgumentError, "unsupported address family: #{family}"
prefix, prefixlen = addr.split('/')
if prefix =~ /^\[(.*)\]$/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)
IPSocket.getaddress(prefix) # test if address is vaild
raise ArgumentError, "invalid address"
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 ArgumentError, "address family mismatch"
@mask_addr = (@family == Socket::AF_INET) ? IN4MASK : IN6MASK
self.class.new(other, @family)