類別 IPAddr
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>
常數
屬性
傳回此 IP 位址的位址家族。
公開類別方法
從字串中的人類可讀 IP 位址表示法或從封裝的 in_addr
值和位址家族建立新的 ipaddr 物件。
在第一種情況下,以下為將被辨識的有效格式:「位址」、「位址/前置長度」和「位址/遮罩」,其中 IPv6 位址可以用方括號(「[」和「]」)括起來。如果指定了前置長度或遮罩,它會傳回一個遮罩 IP 位址。雖然位址系列會自動從指定的字串中決定,但你可以透過選擇性的第二個參數明確指定一個。
否則,IP 位址會從封裝的 in_addr
值和位址系列產生。
IPAddr
類別定義了許多方法和運算子,其中一些,例如 &、|、include? 和 ==,接受字串或封裝的 in_addr
值,而不是 IPAddr
物件。
# File lib/ipaddr.rb, line 593 def initialize(addr = '::', family = Socket::AF_UNSPEC) @mask_addr = nil 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('/', 2) if prefix =~ /\A\[(.*)\]\z/i prefix = $1 family = Socket::AF_INET6 end if prefix =~ /\A(.*)(%\w+)\z/ prefix = $1 zone_id = $2 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 @zone_id = zone_id 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
建立一個新的 ipaddr,其中包含給定的網路位元組順序的 IP 位址字串形式。
# File lib/ipaddr.rb, line 107 def self.new_ntoh(addr) return new(ntop(addr)) end
將網路位元組順序的 IP 位址字串形式轉換為人類可讀的形式。
# File lib/ipaddr.rb, line 113 def self.ntop(addr) case addr.size when 4 addr.unpack('C4').join('.') when 16 IN6FORMAT % addr.unpack('n8') else raise AddressFamilyError, "unsupported address family" end end
公開實例方法
傳回一個透過位元 AND 建立的新 ipaddr。
# File lib/ipaddr.rb, line 125 def &(other) return self.clone.set(@addr & coerce_other(other).to_i) end
傳回一個透過位元左位移建立的新 ipaddr。
# File lib/ipaddr.rb, line 140 def <<(num) return self.clone.set(addr_mask(@addr << num)) end
將 ipaddr 與其他 ipaddr 進行比較。
# File lib/ipaddr.rb, line 386 def <=>(other) other = coerce_other(other) rescue nil else @addr <=> other.to_i if other.family == @family end
如果兩個 ipaddr 相等,傳回 true。
# File lib/ipaddr.rb, line 150 def ==(other) other = coerce_other(other) rescue false else @family == other.family && @addr == other.to_i end
傳回一個透過位元右位移建立的新 ipaddr。
# File lib/ipaddr.rb, line 135 def >>(num) return self.clone.set(@addr >> num) end
檢查 Hash
使用的相等性。
# File lib/ipaddr.rb, line 396 def eql?(other) return self.class == other.class && self.hash == other.hash && self == other end
傳回 IP 位址的網路位元組順序字串形式。
# File lib/ipaddr.rb, line 226 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
如果給定的 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") net4 = IPAddr.new("192.168.2.0/16") p net1.include?(net2) #=> true p net1.include?(net3) #=> false p net1.include?(net4) #=> false p net4.include?(net1) #=> true
# File lib/ipaddr.rb, line 176 def include?(other) other = coerce_other(other) return false unless other.family == family begin_addr <= other.begin_addr && end_addr >= other.end_addr end
傳回包含 ipaddr 人類可讀表示形式的字串。(“#<IPAddr: family:address/mask>”)
# File lib/ipaddr.rb, line 441 def inspect case @family when Socket::AF_INET af = "IPv4" when Socket::AF_INET6 af = "IPv6" zone_id = @zone_id.to_s else raise AddressFamilyError, "unsupported address family" end return sprintf("#<%s: %s:%s%s/%s>", self.class.name, af, _to_string(@addr), zone_id, _to_string(@mask_addr)) end
傳回與 RFC3172 相容的 DNS 反向查詢字串。
# File lib/ipaddr.rb, line 365 def ip6_arpa if !ipv6? raise InvalidAddressError, "not an IPv6 address: #{@addr}" end return _reverse + ".ip6.arpa" end
傳回與 RFC1886 相容的 DNS 反向查詢字串。
# File lib/ipaddr.rb, line 373 def ip6_int if !ipv6? raise InvalidAddressError, "not an IPv6 address: #{@addr}" end return _reverse + ".ip6.int" end
如果 ipaddr 是 IPv4 位址,傳回 true。
# File lib/ipaddr.rb, line 240 def ipv4? return @family == Socket::AF_INET end
傳回透過將原生 IPv4 位址轉換為 IPv4 相容 IPv6 位址而建置的新 ipaddr。
# File lib/ipaddr.rb, line 333 def ipv4_compat warn "IPAddr\##{__callee__} is obsolete", uplevel: 1 if $VERBOSE if !ipv4? raise InvalidAddressError, "not an IPv4 address: #{@addr}" end return self.clone.set(@addr, Socket::AF_INET6) end
如果 ipaddr 是 IPv4 相容 IPv6 位址,傳回 true。
# File lib/ipaddr.rb, line 305 def ipv4_compat? warn "IPAddr\##{__callee__} is obsolete", uplevel: 1 if $VERBOSE _ipv4_compat? end
傳回透過將原生 IPv4 位址轉換為 IPv4 對應 IPv6 位址而建置的新 ipaddr。
# File lib/ipaddr.rb, line 322 def ipv4_mapped if !ipv4? raise InvalidAddressError, "not an IPv4 address: #{@addr}" end clone = self.clone.set(@addr | 0xffff00000000, Socket::AF_INET6) clone.instance_variable_set(:@mask_addr, @mask_addr | 0xffffffffffffffffffffffff00000000) clone end
如果 ipaddr 是 IPv4 對應 IPv6 位址,傳回 true。
# File lib/ipaddr.rb, line 300 def ipv4_mapped? return ipv6? && (@addr >> 32) == 0xffff end
如果 ipaddr 是 IPv6 位址,傳回 true。
# File lib/ipaddr.rb, line 245 def ipv6? return @family == Socket::AF_INET6 end
如果 ipaddr 是連結本機的位址,則傳回 true。RFC 3927 保留的 169.254.0.0/16 中的 IPv4 位址,以及 RFC 4291 保留的 fe80::/10 中的連結本機 IPv6 單播位址,都視為連結本機。
# File lib/ipaddr.rb, line 288 def link_local? case @family when Socket::AF_INET @addr & 0xffff0000 == 0xa9fe0000 # 169.254.0.0/16 when Socket::AF_INET6 @addr & 0xffc0_0000_0000_0000_0000_0000_0000_0000 == 0xfe80_0000_0000_0000_0000_0000_0000_0000 else raise AddressFamilyError, "unsupported address family" end end
如果 ipaddr 是回送位址,則傳回 true。
# File lib/ipaddr.rb, line 250 def loopback? case @family when Socket::AF_INET @addr & 0xff000000 == 0x7f000000 when Socket::AF_INET6 @addr == 1 else raise AddressFamilyError, "unsupported address family" end end
傳回透過使用指定的 prefixlen/網路遮罩對 IP 位址進行遮罩而建置的新 ipaddr。(例如 8、64、「255.255.255.0」等)
# File lib/ipaddr.rb, line 160 def mask(prefixlen) return self.clone.mask!(prefixlen) end
傳回透過將 IPv6 位址轉換為原生 IPv4 位址而建置的新 ipaddr。如果 IP 位址不是 IPv4 對應或 IPv4 相容的 IPv6 位址,則傳回 self。
# File lib/ipaddr.rb, line 344 def native if !ipv4_mapped? && !_ipv4_compat? return self end return self.clone.set(@addr & IN4MASK, Socket::AF_INET) end
傳回字串格式的網路遮罩,例如 255.255.0.0
# File lib/ipaddr.rb, line 456 def netmask _to_string(@mask_addr) end
傳回 ipaddr 的位元前綴長度。
# File lib/ipaddr.rb, line 411 def prefix case @family when Socket::AF_INET n = IN4MASK ^ @mask_addr i = 32 when Socket::AF_INET6 n = IN6MASK ^ @mask_addr i = 128 else raise AddressFamilyError, "unsupported address family" end while n.positive? n >>= 1 i -= 1 end i end
設定位元的 prefix 長度
# File lib/ipaddr.rb, line 430 def prefix=(prefix) case prefix when Integer mask!(prefix) else raise InvalidPrefixError, "prefix must be an integer: #{@addr}" end end
如果 ipaddr 是私人位址,則傳回 true。RFC 1918 中定義的 10.0.0.0/8、172.16.0.0/12 和 192.168.0.0/16 中的 IPv4 位址,以及 RFC 4193 中定義的 fc00::/7 中的 IPv6 唯一本機位址,都視為私人位址。IPv4 對應 IPv6 位址範圍中的私人 IPv4 位址也視為私人位址。
# File lib/ipaddr.rb, line 266 def private? case @family when Socket::AF_INET @addr & 0xff000000 == 0x0a000000 || # 10.0.0.0/8 @addr & 0xfff00000 == 0xac100000 || # 172.16.0.0/12 @addr & 0xffff0000 == 0xc0a80000 # 192.168.0.0/16 when Socket::AF_INET6 @addr & 0xfe00_0000_0000_0000_0000_0000_0000_0000 == 0xfc00_0000_0000_0000_0000_0000_0000_0000 || (@addr & 0xffff_0000_0000 == 0xffff_0000_0000 && ( @addr & 0xff000000 == 0x0a000000 || # ::ffff:10.0.0.0/8 @addr & 0xfff00000 == 0xac100000 || # ::ffff::172.16.0.0/12 @addr & 0xffff0000 == 0xc0a80000 # ::ffff::192.168.0.0/16 )) else raise AddressFamilyError, "unsupported address family" end end
傳回 DNS 反向查詢的字串。對於 IPv6 位址,它會傳回 RFC3172 格式的字串。
# File lib/ipaddr.rb, line 353 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
傳回 ipaddr 的後繼。
# File lib/ipaddr.rb, line 381 def succ return self.clone.set(@addr + 1, @family) end
傳回 ipaddr 的整數表示。
# File lib/ipaddr.rb, line 184 def to_i return @addr end
為網路位址建立 Range
物件。
# File lib/ipaddr.rb, line 406 def to_range self.class.new(begin_addr, @family)..self.class.new(end_addr, @family) end
傳回包含 IP 位址表示的字串。
# File lib/ipaddr.rb, line 189 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
傳回包含正規形式 IP 位址表示的字串。
# File lib/ipaddr.rb, line 215 def to_string str = _to_string(@addr) if @family == Socket::AF_INET6 str << zone_id.to_s end return str end
傳回 IPv6 區域識別碼 (如果存在)。如果不是 IPv6 位址,則會引發 InvalidAddressError
。
# File lib/ipaddr.rb, line 462 def zone_id if @family == Socket::AF_INET6 @zone_id else raise InvalidAddressError, "not an IPv6 address" end end
傳回 IPv6 區域識別碼 (如果存在)。如果不是 IPv6 位址,則會引發 InvalidAddressError
。
# File lib/ipaddr.rb, line 472 def zone_id=(zid) if @family == Socket::AF_INET6 case zid when nil, /\A%(\w+)\z/ @zone_id = zid else raise InvalidAddressError, "invalid zone identifier for address" end else raise InvalidAddressError, "not an IPv6 address" end end
傳回透過按位元 OR 建立的新 ipaddr。
# File lib/ipaddr.rb, line 130 def |(other) return self.clone.set(@addr | coerce_other(other).to_i) end
傳回透過按位元否定建立的新 ipaddr。
# File lib/ipaddr.rb, line 145 def ~ return self.clone.set(addr_mask(~@addr)) end
受保護的執行個體方法
# File lib/ipaddr.rb, line 487 def begin_addr @addr & @mask_addr end
# File lib/ipaddr.rb, line 491 def end_addr case @family when Socket::AF_INET @addr | (IN4MASK ^ @mask_addr) when Socket::AF_INET6 @addr | (IN6MASK ^ @mask_addr) else raise AddressFamilyError, "unsupported address family" end end
設定
目前的網路遮罩為指定的遮罩。
# File lib/ipaddr.rb, line 529 def mask!(mask) case mask when String case mask when /\A(0|[1-9]+\d*)\z/ prefixlen = mask.to_i when /\A\d+\z/ raise InvalidPrefixError, "leading zeros in prefix" else m = IPAddr.new(mask) if m.family != @family raise InvalidPrefixError, "address family is not same: #{@addr}" end @mask_addr = m.to_i n = @mask_addr ^ m.instance_variable_get(:@mask_addr) unless ((n + 1) & n).zero? raise InvalidPrefixError, "invalid mask #{mask}: #{@addr}" end @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: #{@addr}" end masklen = 32 - prefixlen @mask_addr = ((IN4MASK >> masklen) << masklen) when Socket::AF_INET6 if prefixlen < 0 || prefixlen > 128 raise InvalidPrefixError, "invalid length: #{@addr}" end masklen = 128 - prefixlen @mask_addr = ((IN6MASK >> masklen) << masklen) else raise AddressFamilyError, "unsupported address family" end @addr = ((@addr >> masklen) << masklen) return self end
設定
+@addr+,內部儲存的 IP 位址,為指定的 addr
。參數 addr
會使用第一個 family
成員驗證,而該成員為 Socket::AF_INET
或 Socket::AF_INET6
。
# File lib/ipaddr.rb, line 505 def set(addr, *family) case family[0] ? family[0] : @family when Socket::AF_INET if addr < 0 || addr > IN4MASK raise InvalidAddressError, "invalid address: #{@addr}" end when Socket::AF_INET6 if addr < 0 || addr > IN6MASK raise InvalidAddressError, "invalid address: #{@addr}" end else raise AddressFamilyError, "unsupported address family" end @addr = addr if family[0] @family = family[0] if @family == Socket::AF_INET @mask_addr &= IN4MASK end end return self end
私人執行個體方法
# File lib/ipaddr.rb, line 310 def _ipv4_compat? if !ipv6? || (@addr >> 32) != 0 return false end a = (@addr & IN4MASK) return a != 0 && a != 1 end
# File lib/ipaddr.rb, line 716 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
# File lib/ipaddr.rb, line 729 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
# File lib/ipaddr.rb, line 705 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
# File lib/ipaddr.rb, line 642 def coerce_other(other) case other when IPAddr other when String self.class.new(other) else self.class.new(other, @family) end end
# File lib/ipaddr.rb, line 668 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}" 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: #{@addr}" left = $1 right = $2 addr = 0 end else raise InvalidAddressError, "invalid address: #{@addr}" 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
# File lib/ipaddr.rb, line 653 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: #{@addr}" s.match(/\A0./) and raise InvalidAddressError, "zero-filled number in IPv4 address is ambiguous: #{@addr}" i << 8 | n } end