Python 3.3+ipaddressfunction
ipaddress.v4_int_to_packed()
packing to bytes
Converts an integer into the 4 bytes of an IPv4 address in network (big-endian) order.
Syntax
ipaddress.v4_int_to_packed(address)
It is the same as n.to_bytes(4, 'big') or IPv4Address(n).packed, so you rarely need it. A negative number or one of 2**32 and above raises ValueError rather than wrapping around. For the reverse, use IPv4Address(b) or ip_address(b): 4-byte input is read as a packed address.
Examples
import ipaddress
b = ipaddress.v4_int_to_packed(3232235521)
print(b, b == (3232235521).to_bytes(4, 'big')) # → b'\xc0\xa8\x00\x01' True
print(ipaddress.ip_address(b)) # → 192.168.0.1
ipaddress.v4_int_to_packed(2 ** 32) # → ValueError: Address negative or too large for IPv4
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy