Search code examples
pythonhexpacket

Sending hex packets in python


How would I send hex data in a packet? I'm trying to copy a packet exactly by using the hex instead of ASCII. All I'm looking for is what the sendto argument would be if, say, the hex I needed to send was 00AD12.


Solution

  • Use struct to convert between bytes (typically expressed in hexadecimal fashion) and numbers:

    >>> import struct
    >>> struct.pack('!I', 0xAD12)
    b'\x00\x00\xad\x12'
    

    If you have a hex string and want to convert it to bytes, use binascii.unhexlify:

    >>> import binascii
    >>> binascii.unhexlify('ad12')
    b'\xad\x12'