File: ip_address.rb

package info (click to toggle)
ruby-bindata 2.4.14-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 600 kB
  • sloc: ruby: 8,566; makefile: 4
file content (21 lines) | stat: -rw-r--r-- 578 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
require 'bindata'

# A custom type representing an IP address.
# The underlying binary representation is a sequence of four octets.
# The human accessible representation is a dotted quad.
class IPAddr < BinData::Primitive
  array :octets, type: :uint8, initial_length: 4

  def set(val)
    self.octets = val.split(/\./).map(&:to_i)
  end

  def get
    self.octets.map(&:to_s).join(".")
  end
end

ip = IPAddr.new("127.0.0.1")

puts "human readable value:  #{ip}"                     #=> 127.0.0.1
puts "binary representation: #{ip.to_binary_s.inspect}" #=> "\177\000\000\001"