Class: IP
- Inherits:
-
Object
- Object
- IP
- Defined in:
- lib/ip.rb
Constant Summary collapse
- EXPECTED_CIDRS =
%w( 103.21.244.0/22 103.22.200.0/22 103.31.4.0/22 131.0.72.0/22 197.234.240.0/22 173.245.48.0/20 188.114.96.0/20 190.93.240.0/20 108.162.192.0/18 141.101.64.0/18 198.41.128.0/17 162.158.0.0/15 172.64.0.0/13 104.16.0.0/12 )
Instance Attribute Summary collapse
-
#bits ⇒ Object
readonly
Returns the value of attribute bits.
Class Method Summary collapse
Instance Method Summary collapse
-
#includes?(ip_addr) ⇒ Boolean
IP.new(‘192.168.0.1/24’).includes?(IP.new(‘192.168.0.1’)).
-
#initialize(cidr_str) ⇒ IP
constructor
accepts plain IP address, or CIDR notation.
- #sketch? ⇒ Boolean
-
#to_binary ⇒ Object
192.168.0.1 -> 11000000101010000000000000000001.
- #to_s ⇒ Object
Constructor Details
#initialize(cidr_str) ⇒ IP
accepts plain IP address, or CIDR notation
13 14 15 16 |
# File 'lib/ip.rb', line 13 def initialize(cidr_str) @ip, bits = cidr_str.split('/') @bits = bits.to_i if bits end |
Instance Attribute Details
#bits ⇒ Object (readonly)
Returns the value of attribute bits.
10 11 12 |
# File 'lib/ip.rb', line 10 def bits @bits end |
Class Method Details
.expected_cidrs ⇒ Object
37 38 39 |
# File 'lib/ip.rb', line 37 def self.expected_cidrs @cf_ips ||= EXPECTED_CIDRS.map { |cidr| IP.new(cidr) } end |
Instance Method Details
#includes?(ip_addr) ⇒ Boolean
IP.new(‘192.168.0.1/24’).includes?(IP.new(‘192.168.0.1’))
31 32 33 34 35 |
# File 'lib/ip.rb', line 31 def includes?(ip_addr) len = self.bits ip_slice = ->(ip) { ip.to_binary[0,len] } ip_slice.(self) == ip_slice.(ip_addr) end |
#sketch? ⇒ Boolean
26 27 28 |
# File 'lib/ip.rb', line 26 def sketch? @sketch ||= IP.expected_cidrs.none? { |cidr| cidr.includes?(self) } end |
#to_binary ⇒ Object
192.168.0.1 -> 11000000101010000000000000000001
21 22 23 24 |
# File 'lib/ip.rb', line 21 def to_binary n_to_b = ->(n) { n.to_s(2).rjust(BITS_IN_SEGMENT, '0') } @binary_ip ||= @ip.split('.').map { |segment| n_to_b.(segment.to_i) }.join end |
#to_s ⇒ Object
18 |
# File 'lib/ip.rb', line 18 def to_s; @ip; end |