Class: IP::V4

Inherits:
IP
  • Object
show all
Defined in:
lib/ip/base.rb,
lib/ip/socket.rb

Constant Summary collapse

PROTO =
"v4".freeze
ADDR_BITS =
32
MASK =
(1 << ADDR_BITS) - 1
AF =
Socket::AF_INET

Constants inherited from IP

PROTO_TO_CLASS

Instance Attribute Summary

Attributes inherited from IP

#ctx, #pfxlen

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from IP

#&, #+, #-, #<=>, #^, #af, #broadcast, #divide_by_hosts, #divide_by_subnets, #eql?, #freeze, from_cpal, #hash, #initialize, #inspect, #ipv4_compat?, #ipv4_mapped?, #is_in?, #mask, #mask!, #native, #netmask, #network, #offset, #offset?, orig_new, #proto, #reset_pfxlen!, #size, #split, #succ, #succ!, #to_a, #to_addrlen, #to_ah, #to_b, #to_cpal, #to_cphl, #to_hex, #to_i, #to_irange, #to_range, #to_s, #to_sockaddr, #wildmask, #|, #~

Constructor Details

This class inherits a constructor from IP

Class Method Details

.parse(str) ⇒ Object

Parse a string; return an V4 instance if it’s a valid IPv4 address, nil otherwise



325
326
327
328
329
330
331
332
333
334
# File 'lib/ip/base.rb', line 325

def self.parse(str)
  if str =~ /\A(\d+)\.(\d+)\.(\d+)\.(\d+)(?:\/(\d+))?(?:@(.*))?\z/
    pfxlen = ($5 || ADDR_BITS).to_i
    return nil if pfxlen > 32
    addrs = [$1.to_i, $2.to_i, $3.to_i, $4.to_i]
    return nil if addrs.find { |n| n>255 }
    addr = (((((addrs[0] << 8) | addrs[1]) << 8) | addrs[2]) << 8) | addrs[3]
    new(addr, pfxlen, $6)
  end
end

Instance Method Details

#to_addrObject

Return just the address part as a String in dotted decimal form



337
338
339
340
# File 'lib/ip/base.rb', line 337

def to_addr
  sprintf("%d.%d.%d.%d",
    (@addr>>24)&0xff, (@addr>>16)&0xff, (@addr>>8)&0xff, @addr&0xff)
end

#to_arpaObject

return the arpa version of the address for reverse DNS: en.wikipedia.org/wiki/Reverse_DNS_lookup



342
343
344
345
# File 'lib/ip/base.rb', line 342

def to_arpa
  sprintf("%d.%d.%d.%d.in-addr.arpa.",
    @addr&0xff, (@addr>>8)&0xff, (@addr>>16)&0xff,(@addr>>24)&0xff)
end