Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Send Integer value over socket

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

like image 443
marlow Avatar asked Sep 11 '26 09:09

marlow


1 Answers

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.

like image 92
user3820547 Avatar answered Sep 13 '26 23:09

user3820547



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!