3

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

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Hey, thank you for your response, As far as I can tell, I think that's what I wanted!
0

you could use bytes(). Thats what I use to send strings over a network but you can use it for ints as well. Its usage is bytes([3])

Edit: bytes converts an int (3) to bytes. a string of bytes is represented as b'\x03'. so like your byte string: 0x12345678 would be b'\x12345678'

check the docs for more info: https://docs.python.org/3.1/library/functions.html#bytes

1 Comment

I'm not quite sure this is what I want, but I appreciate your response. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.