Python: Send Integer value over socket

hex, integer, python, sockets, tcp

Solution

The main method to send binary data in Python is using the struct module.

For example, packing 3 4-byte unsigned integers is done like this

In [3]: struct.pack("III", 3, 4, 5)
Out[3]: '\x03\x00\x00\x00\x04\x00\x00\x00\x05\x00\x00\x00'

Note to keep the endianess correct, using "<", ">", and so on.

Problem

I'm using Python to communicate data over a TCP socket between a server and client application. I need to send a 4 bytes which represent a data sample. The initial sample is an 32-bit unsigned integer. How can I send those 4 bytes of raw data through the socket? I want to send the data: 0x12345678 and 0xFEDCBA98 The raw data sent over the socket should be exactly that if I read it on wireshark/tcpdump/etc. I don't want each value in the 8 hex numbers to be represented as an ascii character, I want the raw data to remain intact. Thank you

Original source