Skip to content

packet

Packet framing utilities for byte streams.

This module provides functions to write and read length-prefixed packets over file descriptors using IOStream. Each packet is framed with an 8-byte little-endian unsigned length prefix followed by the raw payload data.

write_packet(fd, data)

Write a length-prefixed packet to a file descriptor.

The packet consists of an 8-byte little-endian unsigned length prefix followed by the raw data bytes.

Parameters:

Name Type Description Default
fd

The file descriptor or stream to write to.

required
data

The payload bytes to write.

required
Source code in py_misc_utils/packet.py
15
16
17
18
19
20
21
22
23
24
25
26
27
def write_packet(fd, data):
  """Write a length-prefixed packet to a file descriptor.

  The packet consists of an 8-byte little-endian unsigned length prefix
  followed by the raw data bytes.

  Args:
    fd: The file descriptor or stream to write to.
    data: The payload bytes to write.
  """
  packet = _SIZE_PACKER.pack(len(data)) + data
  iofd = ios.IOStream(fd)
  iofd.write(packet)

read_packet(fd)

Read a length-prefixed packet from a file descriptor.

Reads an 8-byte little-endian unsigned length prefix, then reads that many bytes of payload.

Parameters:

Name Type Description Default
fd

The file descriptor or stream to read from.

required

Returns:

Type Description

The payload bytes of the packet.

Source code in py_misc_utils/packet.py
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
def read_packet(fd):
  """Read a length-prefixed packet from a file descriptor.

  Reads an 8-byte little-endian unsigned length prefix, then reads that many
  bytes of payload.

  Args:
    fd: The file descriptor or stream to read from.

  Returns:
    The payload bytes of the packet.
  """
  iofd = ios.IOStream(fd)
  data = iofd.read(_SIZE_PACKER.size)
  size = _SIZE_PACKER.unpack(data)[0]
  packet = iofd.read(size)

  return packet