Michael
Michael

Reputation: 157

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.

Upvotes: 6

Views: 18200

Answers (1)

phihag
phihag

Reputation: 288190

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'

Upvotes: 12

Related Questions