Class: NetAddr::IPv4

Inherits:
Object
  • Object
show all
Defined in:
lib/ipv4.rb

Overview

IPv4 represents a single IPv4 address.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(i) ⇒ IPv4

Create an IPv4 from an Integer. Must be between 0 and 2**32-1. Throws ValidationError on error.



10
11
12
13
14
15
16
17
# File 'lib/ipv4.rb', line 10

def initialize(i)
	if (!i.kind_of?(Integer))
		raise ValidationError, "Expected an Integer for 'i' but got a #{i.class}."
	elsif ( (i < 0) || (i > 2**32-1) )
		raise ValidationError, "#{i} is out of bounds for IPv4."
	end
	@addr = i
end

Instance Attribute Details

#addrObject (readonly)

addr is the Integer representation of this IP address



6
7
8
# File 'lib/ipv4.rb', line 6

def addr
  @addr
end

Class Method Details

.parse(ip) ⇒ Object

parse will create an IPv4 from its string representation (ie. “192.168.1.1”). Throws ValidationError on error.



21
22
23
24
25
# File 'lib/ipv4.rb', line 21

def IPv4.parse(ip)
	ip = ip.strip
	i = Util.parse_IPv4(ip)
	return IPv4.new(i)
end

Instance Method Details

#cmp(other) ⇒ Object

cmp compares equality with another IPv4. Return:

  • 1 if this IPv4 is numerically greater

  • 0 if the two are equal

  • -1 if this IPv4 is numerically less



31
32
33
34
35
36
37
38
39
40
41
# File 'lib/ipv4.rb', line 31

def cmp(other)
	if (!other.kind_of?(IPv4))
		raise ArgumentError, "Expected an IPv4 object for 'other' but got a #{other.class}."
	end
	if (self.addr > other.addr)
		return 1
	elsif (self.addr < other.addr)
		return -1
	end
	return 0
end

#multicast_macObject

multicast_mac returns the EUI48 multicast mac-address for this IP. It will return the zero address for IPs outside of the multicast range 224.0.0.0/4.



45
46
47
48
49
50
51
52
# File 'lib/ipv4.rb', line 45

def multicast_mac
	mac = 0
	if (@addr&0xf0000000 == 0xe0000000) # within 224.0.0.0/4 ?
		# map lower 23-bits of ip to 01:00:5e:00:00:00
		mac = (@addr&0x007fffff) | 0x01005e000000
	end
	return EUI48.new(mac)
end

#nextObject

next returns the next consecutive IPv4 or nil if the address space is exceeded



55
56
57
58
59
60
# File 'lib/ipv4.rb', line 55

def next()
	if (self.addr == NetAddr::F32)
		return nil
	end
	return IPv4.new(self.addr + 1)
end

#prevObject

prev returns the preceding IPv4 or nil if this is 0.0.0.0



63
64
65
66
67
68
# File 'lib/ipv4.rb', line 63

def prev()
	if (self.addr == 0)
		return nil
	end
	return IPv4.new(self.addr - 1)
end

#to_netObject

to_net returns the IPv4 as a IPv4Net



71
72
73
# File 'lib/ipv4.rb', line 71

def to_net()
	NetAddr::IPv4Net.new(self,nil)
end

#to_sObject

to_s returns the IPv4 as a String



76
77
78
# File 'lib/ipv4.rb', line 76

def to_s()
	Util.int_to_IPv4(@addr)
end

#versionObject

version returns “4” for IPv4



81
82
83
# File 'lib/ipv4.rb', line 81

def version()
	return 4
end