Class: IP::V4

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

Constant Summary collapse

PROTO =
'v4'
ADDR_MAX =
4_294_967_295
ADDR_BITS =
32
MASK =
(1 << ADDR_BITS) - 1
ARPA =
'.in-addr.arpa.'
AF =
Socket::AF_INET

Constants inherited from IP

PROTO_TO_CLASS, VERSION

Instance Attribute Summary

Attributes inherited from IP

#ctx, #pfxlen

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from IP

#&, #+, #-, #<=>, #^, #af, #broadcast, #deaggregate, #divide_by_hosts, #divide_by_subnets, #eql?, #freeze, from_cpal, #hash, #initialize, #inspect, #ipv4_compat?, #ipv4_mapped?, #is_in?, #mask, #mask!, #native, #netmask, #network, new_ntoh, ntop, #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



394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
# File 'lib/ip/base.rb', line 394

def self.parse(str)
  if str =~ %r{\A(\d+)\.(\d+)\.(\d+)\.(\d+)(?:/(\d+))?(?:@(.*))?\z}
    pfxlen = (Regexp.last_match[5] || ADDR_BITS).to_i
    return nil if pfxlen > 32

    addrs = [Regexp.last_match[1].to_i,
             Regexp.last_match[2].to_i,
             Regexp.last_match[3].to_i,
             Regexp.last_match[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, Regexp.last_match[6])
  end
end

Instance Method Details

#htonObject

Returns a network byte ordered string form of the IP address.



429
430
431
# File 'lib/ip/base.rb', line 429

def hton
  [@addr].pack('N')
end

#to_addrObject

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



411
412
413
414
415
416
417
# File 'lib/ip/base.rb', line 411

def to_addr
  format('%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



420
421
422
423
424
425
426
# File 'lib/ip/base.rb', line 420

def to_arpa
  format("%d.%d.%d.%d#{ARPA}",
         @addr & 0xff,
         (@addr >> 8) & 0xff,
         (@addr >> 16) & 0xff,
         (@addr >> 24) & 0xff)
end