UDP (User Datagram Protocol) datagram: Ruby parsing library

UDP is a simple stateless transport layer (AKA OSI layer 4) protocol, one of the core Internet protocols. It provides source and destination ports, basic checksumming, but provides not guarantees of delivery, order of packets, or duplicate delivery.

KS implementation details

License: CC0-1.0

This page hosts a formal specification of UDP (User Datagram Protocol) datagram using Kaitai Struct. This specification can be automatically translated into a variety of programming languages to get a parsing library.

Usage

Parse a local file and get structure in memory:

data = UdpDatagram.from_file("path/to/local/file.UDP (User Datagram Protocol) datagram")

Or parse structure from a string of bytes:

bytes = "\x00\x01\x02..."
data = UdpDatagram.new(Kaitai::Struct::Stream.new(bytes))

After that, one can get various attributes from the structure by invoking getter methods like:

data.src_port # => get src port

Ruby source code to parse UDP (User Datagram Protocol) datagram

udp_datagram.rb

# This is a generated file! Please edit source .ksy file and use kaitai-struct-compiler to rebuild

require 'kaitai/struct/struct'

unless Gem::Version.new(Kaitai::Struct::VERSION) >= Gem::Version.new('0.7')
  raise "Incompatible Kaitai Struct Ruby API: 0.7 or later is required, but you have #{Kaitai::Struct::VERSION}"
end


##
# UDP is a simple stateless transport layer (AKA OSI layer 4)
# protocol, one of the core Internet protocols. It provides source and
# destination ports, basic checksumming, but provides not guarantees
# of delivery, order of packets, or duplicate delivery.
class UdpDatagram < Kaitai::Struct::Struct
  def initialize(_io, _parent = nil, _root = self)
    super(_io, _parent, _root)
    _read
  end

  def _read
    @src_port = @_io.read_u2be
    @dst_port = @_io.read_u2be
    @length = @_io.read_u2be
    @checksum = @_io.read_u2be
    @body = @_io.read_bytes_full
    self
  end
  attr_reader :src_port
  attr_reader :dst_port
  attr_reader :length
  attr_reader :checksum
  attr_reader :body
end