Ruby 2.4

IPAddr

class IPAddr

Parent:ObjectIncluded modules:Comparable

IPAddr 提供了一组操作 IP 地址的方法。支持 IPv4和 IPv6。

require 'ipaddr' 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>

常量

IN4MASK

IPv4的32位掩码

IN6FORMAT

IPv6的格式字符串

IN6MASK

IPv6 的128位掩码

RE_IPV4ADDRLIKE

Regexp 内部用于解析 IPv4地址。

RE_IPV6ADDRLIKE_COMPRESSED

Regexp 内部用于解析 IPv6 地址。

RE_IPV6ADDRLIKE_FULL

Regexp 内部用于解析 IPv6 地址。

属性

familyR

返回此 IP 地址的地址族。

公共类方法

new(addr = '::', family = Socket::AF_UNSPEC) Show source

通过字符串中的可读 IP 地址表示形式或者从紧随地址系列的压缩的 #in_addr 值创建新的 ipaddr 对象。

在前一种情况下,以下是将被识别的有效格式:“address”,“address / prefixlen” 和 “address / mask”,其中 IPv6 地址可以用方括号([' and]' 括起来)。如果指定了 prefixlen 或mask,它将返回一个被屏蔽的 IP 地址。虽然地址族是从指定的字符串中自动确定的,但您可以通过可选的第二个参数明确指定地址族。

否则,IP 地址将从打包的#in_addr 值和地址族中生成。

IPAddr 类定义了许多方法和运算符,其中一些(如&,|)包含?和==,接受一个字符串或打包的#in_addr 值而不是 IPAddr 对象。

# File lib/ipaddr.rb, line 470 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/i prefix = $1 family = Socket::AF_INET6 end # It seems AI_NUMERICHOST doesn't do the job. #Socket.getaddrinfo(left, nil, Socket::AF_INET6, Socket::SOCK_STREAM, nil, # Socket::AI_NUMERICHOST) @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

new_ntoh(addr) Show source

创建一个新的 ipaddr,其中包含给定的网络字节顺序字符串形式的 IP 地址。

# File lib/ipaddr.rb, line 105 def IPAddr::new_ntoh(addr) return IPAddr.new(IPAddr::ntop(addr)) end

ntop(addr) Show source

将网络字节有序的字符串形式的 IP 地址转换为可读形式。

# File lib/ipaddr.rb, line 111 def IPAddr::ntop(addr) case addr.size when 4 s = addr.unpack('C4').join('.') when 16 s = IN6FORMAT % addr.unpack('n8') else raise AddressFamilyError, "unsupported address family" end return s end

公共实例方法

&(other) Show source

返回按位 AND 创建的新 ipaddr。

# File lib/ipaddr.rb, line 124 def &(other) return self.clone.set(@addr & coerce_other(other).to_i) end

<<(num) Show source

返回按位左移建立的新 ipaddr。

# File lib/ipaddr.rb, line 139 def <<(num) return self.clone.set(addr_mask(@addr << num)) end

<=>(other) Show source

将 ipaddr 与另一个进行比较。

# File lib/ipaddr.rb, line 338 def <=>(other) other = coerce_other(other) rescue nil else @addr <=> other.to_i if other.family == @family end

==(other) Show source

如果两个 ipaddrs 相等,则返回 true。

# File lib/ipaddr.rb, line 149 def ==(other) other = coerce_other(other) rescue false else @family == other.family && @addr == other.to_i end

===(other)

Alias for: include?

(num) Show source

返回按位右移建立的新 ipaddr。

# File lib/ipaddr.rb, line 134 def >>(num) return self.clone.set(@addr >> num) end

eql?(other) Show source

检查哈希使用的相等性。

# File lib/ipaddr.rb, line 348 def eql?(other) return self.class == other.class && self.hash == other.hash && self == other end

hash() Show source

返回由 Hash,Set 和 Array 类使用的散列值

# File lib/ipaddr.rb, line 353 def hash return ([@addr, @mask_addr].hash << 1) | (ipv4? ? 0 : 1) end

hton() Show source

返回 IP 地址的网络字节有序字符串形式。

# File lib/ipaddr.rb, line 238 def hton case @family when Socket::AF_INET return [@addr].pack('N') when Socket::AF_INET6 return (0..7).map { |i| (@addr >> (112 - 16 * i)) & 0xffff }.pack('n8') else raise AddressFamilyError, "unsupported address family" end end

include?(other) Show source

如果给定的 ipaddr 在范围内,则返回 true。

例如:

require 'ipaddr' 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

# File lib/ipaddr.rb, line 172 def include?(other) other = coerce_other(other) if ipv4_mapped? if (@mask_addr >> 32) != 0xffffffffffffffffffffffff return false end mask_addr = (@mask_addr & IN4MASK) addr = (@addr & IN4MASK) family = Socket::AF_INET else mask_addr = @mask_addr addr = @addr family = @family end if other.ipv4_mapped? other_addr = (other.to_i & IN4MASK) other_family = Socket::AF_INET else other_addr = other.to_i other_family = other.family end if family != other_family return false end return ((addr & mask_addr) == (other_addr & mask_addr)) end

Also aliased as: ===

inspect() Show source

返回包含 ipaddr 的人类可读表示的字符串。(“#<IPAddr:family:address / mask>”)

# File lib/ipaddr.rb, line 375 def inspect case @family when Socket::AF_INET af = "IPv4" when Socket::AF_INET6 af = "IPv6" else raise AddressFamilyError, "unsupported address family" end return sprintf("#<%s: %s:%s/%s>", self.class.name, af, _to_string(@addr), _to_string(@mask_addr)) end

ip6_arpa() Show source

返回与 RFC3172兼容的 DNS 反向查找字符串。

# File lib/ipaddr.rb, line 317 def ip6_arpa if !ipv6? raise InvalidAddressError, "not an IPv6 address" end return _reverse + ".ip6.arpa" end

ip6_int() Show source

返回与 RFC1886兼容的 DNS 反向查找字符串。

# File lib/ipaddr.rb, line 325 def ip6_int if !ipv6? raise InvalidAddressError, "not an IPv6 address" end return _reverse + ".ip6.int" end

ipv4?() Show source

如果 ipaddr 是 IPv4地址,则返回 true。

# File lib/ipaddr.rb, line 252 def ipv4? return @family == Socket::AF_INET end

ipv4_compat() Show source

返回通过将本地 IPv4地址转换为兼容 IPv4的 IPv6地址构建的新 ipaddr。

# File lib/ipaddr.rb, line 286 def ipv4_compat if !ipv4? raise InvalidAddressError, "not an IPv4 address" end return self.clone.set(@addr, Socket::AF_INET6) end

ipv4_compat?() Show source

如果 ipaddr 是 IPv4兼容的 IPv6地址,则返回 true。

# File lib/ipaddr.rb, line 267 def ipv4_compat? if !ipv6? || (@addr >> 32) != 0 return false end a = (@addr & IN4MASK) return a != 0 && a != 1 end

ipv4_mapped() Show source

通过将本地 IPv4地址转换为 IPv4映射的 IPv6地址来返回新的 ipaddr。

# File lib/ipaddr.rb, line 277 def ipv4_mapped if !ipv4? raise InvalidAddressError, "not an IPv4 address" end return self.clone.set(@addr | 0xffff00000000, Socket::AF_INET6) end

ipv4_mapped?() Show source

如果 ipaddr 是 IPv4 映射的 IPv6 地址,则返回 true。

# File lib/ipaddr.rb, line 262 def ipv4_mapped? return ipv6? && (@addr >> 32) == 0xffff end

ipv6?() Show source

如果 ipaddr 是 IPv6地址,则返回 true。

# File lib/ipaddr.rb, line 257 def ipv6? return @family == Socket::AF_INET6 end

mask(prefixlen) Show source

通过使用给定的 prefixlen / netmask 掩码 IP 地址返回一个新的 ipaddr。(例如8,64,“255.255.255.0”等)

# File lib/ipaddr.rb, line 159 def mask(prefixlen) return self.clone.mask!(prefixlen) end

native() Show source

通过将 IPv6地址转换为本地 IPv4地址来返回一个新的 ipaddr。如果 IP 地址不是 IPv4映射或 IPv4兼容的 IPv6地址,则返回 self。

# File lib/ipaddr.rb, line 296 def native if !ipv4_mapped? && !ipv4_compat? return self end return self.clone.set(@addr & IN4MASK, Socket::AF_INET) end

reverse() Show source

返回 DNS 反向查找的字符串。它以 RFC3172格式为 IPv6地址返回一个字符串。

# File lib/ipaddr.rb, line 305 def reverse case @family when Socket::AF_INET return _reverse + ".in-addr.arpa" when Socket::AF_INET6 return ip6_arpa else raise AddressFamilyError, "unsupported address family" end end

succ() Show source

返回 ipaddr 的后继者。

# File lib/ipaddr.rb, line 333 def succ return self.clone.set(@addr + 1, @family) end

to_i() Show source

返回 ipaddr 的整数表示形式。

# File lib/ipaddr.rb, line 202 def to_i return @addr end

to_range() Show source

为网络地址创建一个 Range 对象。

# File lib/ipaddr.rb, line 358 def to_range begin_addr = (@addr & @mask_addr) case @family when Socket::AF_INET end_addr = (@addr | (IN4MASK ^ @mask_addr)) when Socket::AF_INET6 end_addr = (@addr | (IN6MASK ^ @mask_addr)) else raise AddressFamilyError, "unsupported address family" end return clone.set(begin_addr, @family)..clone.set(end_addr, @family) end

to_s() Show source

返回包含 IP 地址表示的字符串。

# File lib/ipaddr.rb, line 207 def to_s str = to_string return str if ipv4? str.gsub!(/\b0{1,3}([\da-f]+)\b/i, '\1') loop do 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/, ':') break end str.sub!(/:{3,}/, '::') 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) end str end

to_string() Show source

以规范形式返回包含 IP 地址表示形式的字符串。

# File lib/ipaddr.rb, line 233 def to_string return _to_string(@addr) end

|(other) Show source

返回按位 OR 创建的新 ipaddr。

# File lib/ipaddr.rb, line 129 def |(other) return self.clone.set(@addr | coerce_other(other).to_i) end

~() Show source

返回按位否定构建的新 ipaddr。

# File lib/ipaddr.rb, line 144 def ~ return self.clone.set(addr_mask(~@addr)) end

受保护的实例方法

mask!(mask) Show source

Set current netmask to given mask.

# File lib/ipaddr.rb, line 414 def mask!(mask) if mask.kind_of?(String) if mask =~ /\A\d+\z/ prefixlen = mask.to_i else m = IPAddr.new(mask) if m.family != @family raise InvalidPrefixError, "address family is not same" end @mask_addr = m.to_i @addr &= @mask_addr return self end else prefixlen = mask end case @family when Socket::AF_INET if prefixlen < 0 || prefixlen > 32 raise InvalidPrefixError, "invalid length" end masklen = 32 - prefixlen @mask_addr = ((IN4MASK >> masklen) << masklen) when Socket::AF_INET6 if prefixlen < 0 || prefixlen > 128 raise InvalidPrefixError, "invalid length" end masklen = 128 - prefixlen @mask_addr = ((IN6MASK >> masklen) << masklen) else raise AddressFamilyError, "unsupported address family" end @addr = ((@addr >> masklen) << masklen) return self end

set(addr, *family) Show source

设置+ @ addr +,内部存储的IP地址,给定addr。该参数addr使用第一个family成员进行验证,该成员是Socket::AF_INETSocket::AF_INET6

# File lib/ipaddr.rb, line 393 def set(addr, *family) case family[0] ? family[0] : @family when Socket::AF_INET if addr < 0 || addr > IN4MASK raise InvalidAddressError, "invalid address" end when Socket::AF_INET6 if addr < 0 || addr > IN6MASK raise InvalidAddressError, "invalid address" end else raise AddressFamilyError, "unsupported address family" end @addr = addr if family[0] @family = family[0] end return self end

私有实例方法

_reverse() Show source

# File lib/ipaddr.rb, line 586 def _reverse case @family when Socket::AF_INET return (0..3).map { |i| (@addr >> (8 * i)) & 0xff }.join('.') when Socket::AF_INET6 return ("%.32x" % @addr).reverse!.gsub!(/.(?!$)/, '\&.') else raise AddressFamilyError, "unsupported address family" end end

_to_string(addr) Show source

# File lib/ipaddr.rb, line 599 def _to_string(addr) case @family when Socket::AF_INET return (0..3).map { |i| (addr >> (24 - 8 * i)) & 0xff }.join('.') when Socket::AF_INET6 return (("%.32x" % addr).gsub!(/.{4}(?!$)/, '\&:')) else raise AddressFamilyError, "unsupported address family" end end

addr_mask(addr) Show source

# File lib/ipaddr.rb, line 575 def addr_mask(addr) case @family when Socket::AF_INET return addr & IN4MASK when Socket::AF_INET6 return addr & IN6MASK else raise AddressFamilyError, "unsupported address family" end end

coerce_other(other) Show source

# File lib/ipaddr.rb, line 512 def coerce_other(other) case other when IPAddr other when String self.class.new(other) else self.class.new(other, @family) end end

in6_addr(left) Show source

# File lib/ipaddr.rb, line 538 def in6_addr(left) case left when RE_IPV6ADDRLIKE_FULL if $2 addr = in_addr($~[2,4]) left = $1 + ':' else addr = 0 end right = '' when RE_IPV6ADDRLIKE_COMPRESSED if $4 left.count(':') <= 6 or raise InvalidAddressError, "invalid address" addr = in_addr($~[4,4]) left = $1 right = $3 + '0:0' else left.count(':') <= ($1.empty? || $2.empty? ? 8 : 7) or raise InvalidAddressError, "invalid address" left = $1 right = $2 addr = 0 end else raise InvalidAddressError, "invalid address" end l = left.split(':') r = right.split(':') rest = 8 - l.size - r.size if rest < 0 return nil end (l + Array.new(rest, '0') + r).inject(0) { |i, s| i << 16 | s.hex } | addr end

in_addr(addr) Show source

# File lib/ipaddr.rb, line 523 def in_addr(addr) case addr when Array octets = addr else m = RE_IPV4ADDRLIKE.match(addr) or return nil octets = m.captures end octets.inject(0) { |i, s| (n = s.to_i) < 256 or raise InvalidAddressError, "invalid address" s.match(/\A0./) and raise InvalidAddressError, "zero-filled number in IPv4 address is ambiguous" i << 8 | n } end