Encode and decode XDR data using Python xdrlib

The External Data Representation (XDR) is a standard data serialization format used for transporting data between different systems. Python's xdrlib module provides encoders and decoders for XDR format, making it useful for creating and transferring complex data structures across networks.

XDR provides a service associated with the OSI Presentation Layer and ensures consistent data representation regardless of the underlying system architecture.

Basic XDR Packing and Unpacking

The following example demonstrates how to pack and unpack data using the xdrlib module ?

import xdrlib

# Create a packer object
packer = xdrlib.Packer()
print("Packer type:", type(packer))

# Pack a list of integers
numbers = [1, 2, 3]
packer.pack_list(numbers, packer.pack_int)

# Get the packed data
packed_data = packer.get_buffer()
print("Packed data:", packed_data)

# Create an unpacker object
unpacker = xdrlib.Unpacker(packed_data)
print("Unpacker type:", type(unpacker))

# Unpack the data
unpacked_numbers = unpacker.unpack_list(unpacker.unpack_int)
print("Original list:", numbers)
print("Unpacked list:", unpacked_numbers)
Packer type: <class 'xdrlib.Packer'>
Packed data: b'\x00\x00\x00\x03\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x03'
Unpacker type: <class 'xdrlib.Unpacker'>
Original list: [1, 2, 3]
Unpacked list: [1, 2, 3]

Packing Different Data Types

XDR supports various data types including strings, floats, and booleans ?

import xdrlib

# Create packer
packer = xdrlib.Packer()

# Pack different data types
packer.pack_int(42)
packer.pack_string(b"Hello XDR")
packer.pack_float(3.14159)
packer.pack_bool(True)

# Get packed data
data = packer.get_buffer()
print("Packed data length:", len(data), "bytes")

# Create unpacker and retrieve data
unpacker = xdrlib.Unpacker(data)
integer_val = unpacker.unpack_int()
string_val = unpacker.unpack_string()
float_val = unpacker.unpack_float()
bool_val = unpacker.unpack_bool()

print("Integer:", integer_val)
print("String:", string_val)
print("Float:", float_val)
print("Boolean:", bool_val)
Packed data length: 32 bytes
Integer: 42
String: b'Hello XDR'
Float: 3.1415898799896240
Boolean: True

Key Methods

Method Purpose Data Type
pack_int() Pack signed integer 32-bit integer
pack_string() Pack byte string Variable length bytes
pack_float() Pack floating point IEEE 754 single precision
pack_list() Pack list of items Sequence of elements

Conclusion

Python's xdrlib module provides a straightforward way to serialize and deserialize data using the XDR format. It's particularly useful for network communication and cross-platform data exchange where consistent data representation is crucial.

Updated on: 2026-03-15T18:32:40+05:30

719 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements