[plum.ipv4] Tutorial: IPV4 Address Type

This tutorial teaches how to use the plum type classes provided by the plum.ipv4 subpackage for packing and unpacking IPV4 addresses.

IPV4 Address Byte Order

The plum.ipv4 subpackage includes three modules, one for each endian byte order: plum.ipv4.big, plum.ipv4.little, and plum.ipv4.native (native byte order follows host architecture). Each module provides a plum type class for IPV4 addresses: IpV4Address. This tutorial demonstrates the big endian variant. The little endian variant has identical features except reversed byte order.

Unpacking Bytes

The plum IPV4 address types convert bytes into Python IpV4Address instances when used with the various plum unpacking mechanisms. For example:

>>> from plum import unpack, Buffer
>>> from plum.ipv4.big import IpV4Address
>>>
>>> # utility function
>>> unpack(IpV4Address, b'\x01\x02\x03\x04')
IpV4Address('1.2.3.4')
>>>
>>> # class method
>>> IpV4Address.unpack(b'\x01\x02\x03\x04')
IpV4Address('1.2.3.4')
>>>
>>> # bytes buffer
>>> with Buffer(b'\x01\x02\x03\x04') as buffer:
...     address = buffer.unpack(IpV4Address)
...
>>> address
IpV4Address('1.2.3.4')

Packing Bytes

The plum IPV4 address types convert strings, integers, or iterables into bytes when used with the various plum packing mechanisms. For example:

>>> from plum import pack
>>> from plum.ipv4.big import IpV4Address
>>>
>>> # utility function (packing a string)
>>> pack(IpV4Address, '1.2.3.4')
bytearray(b'\x01\x02\x03\x04')
>>>
>>> # class method (packing an integer)
>>> IpV4Address.pack(0x1020304)
bytearray(b'\x01\x02\x03\x04')
>>>
>>> # instance method (with iterable)
>>> IpV4Address([4, 3, 2, 1]).pack()
bytearray(b'\x01\x02\x03\x04')

Instantiation and Instance Properties

plum IPV4 address constructors accept strings, integers, or iterables. The representation of the instance includes the class name to differentiate it from a standard Python string:

>>> from plum.ipv4.big import IpV4Address
>>>
>>> # string
>>> IpV4Address('1.2.3.4')
IpV4Address('1.2.3.4')
>>>
>>> # integer
>>> IpV4Address(0x1020304)
IpV4Address('1.2.3.4')
>>>
>>> # iterable
>>> IpV4Address([4, 3, 2, 1])
IpV4Address('1.2.3.4')

Instances support the pack() method:

>>> address = IpV4Address('1.2.3.4')
>>> address.pack()
bytearray(b'\x01\x02\x03\x04')

Instances support bit mask operations:

>>> address = IpV4Address('1.2.3.4')
>>> address & 0xffffff00
IpV4Address('1.2.3.0')
>>>
>>> address |= 0xff
>>> address
IpV4Address('1.2.3.255')

Instances support conversions to int, float, and bool:

>>> address = IpV4Address('1.2.3.4')
>>> int(address)
16909060
>>>
>>> float(address)
16909060.0
>>>
>>> bool(address)
True

Instances support iterating the octets and access via indexing:

>>> address = IpV4Address('1.2.3.4')
>>>
>>> list(address)
[4, 3, 2, 1]
>>>
>>> len(address)
4
>>>
>>> address[3] = 99
>>> address
IpV4Address('99.2.3.4')