Class: PacketGen::Header::IP::Addr

Inherits:
Struct
  • Object
show all
Includes:
StructFu
Defined in:
lib/packetgen/header/ip.rb

Overview

IP address, as a group of 4 bytes

Author:

  • Sylvain Daubert

Constant Summary collapse

IPV4_ADDR_REGEX =
/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from StructFu

#body=, #clone, #set_endianness, #sz, #to_s, #typecast

Methods inherited from Struct

#force_binary

Constructor Details

#initialize(options = {}) ⇒ Addr

Returns a new instance of Addr.

Parameters:

  • options (Hash) (defaults to: {})

Options Hash (options):

  • :a1 (Integer)
  • :a2 (Integer)
  • :a3 (Integer)
  • :a4 (Integer)


79
80
81
82
83
84
85
# File 'lib/packetgen/header/ip.rb', line 79

def initialize(options={})
  super Int8.new(options[:a1]),
        Int8.new(options[:a2]),
        Int8.new(options[:a3]),
        Int8.new(options[:a4])

end

Instance Attribute Details

#a1Object

Returns the value of attribute a1

Returns:

  • (Object)

    the current value of a1



69
70
71
# File 'lib/packetgen/header/ip.rb', line 69

def a1
  @a1
end

#a2Object

Returns the value of attribute a2

Returns:

  • (Object)

    the current value of a2



69
70
71
# File 'lib/packetgen/header/ip.rb', line 69

def a2
  @a2
end

#a3Object

Returns the value of attribute a3

Returns:

  • (Object)

    the current value of a3



69
70
71
# File 'lib/packetgen/header/ip.rb', line 69

def a3
  @a3
end

#a4Object

Returns the value of attribute a4

Returns:

  • (Object)

    the current value of a4



69
70
71
# File 'lib/packetgen/header/ip.rb', line 69

def a4
  @a4
end

Instance Method Details

#from_human(str) ⇒ self

Read a dotted address

Parameters:

Returns:

  • (self)


90
91
92
93
94
95
96
97
98
99
100
# File 'lib/packetgen/header/ip.rb', line 90

def from_human(str)
  return self if str.nil?
  m = str.match(IPV4_ADDR_REGEX)
  if m
    self[:a1].read m[1].to_i
    self[:a2].read m[2].to_i
    self[:a3].read m[3].to_i
    self[:a4].read m[4].to_i
  end
  self
end

#read(str) ⇒ self

Read a Addr from a string

Parameters:

  • str (String)

    binary string

Returns:

  • (self)

Raises:



105
106
107
108
109
110
111
112
# File 'lib/packetgen/header/ip.rb', line 105

def read(str)
  return self if str.nil?
  raise ParseError, 'string too short for IP::Addr' if str.size < self.sz
  force_binary str
  [:a1, :a2, :a3, :a4].each_with_index do |byte, i|
    self[byte].read str[i, 1]
  end
end

#to_humanString

Addr in human readable form (dotted format)

Returns:



121
122
123
# File 'lib/packetgen/header/ip.rb', line 121

def to_human
  members.map { |m| "#{self[m].to_i}" }.join('.')
end

#to_iInteger

Addr as an integer

Returns:

  • (Integer)


127
128
129
130
# File 'lib/packetgen/header/ip.rb', line 127

def to_i
  (self.a1 << 24) | (self.a2 << 16) | (self.a3 << 8) |
    self.a4
end