Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Idiom for socket receive in Python

Tags:

python

c

sockets

I have some experience with socket programming using the Berkeley socket API in C. Generally, any socket programming requires a strategy that enables the receiving socket to know how much data it should receive. This can be accomplished with either header length fields, or delimiter characters. Generally, I prefer a header field which contains the length.

Of course, we also need to know the size of the length header field itself, which is simply a fixed size value that must be agreed upon by both sender and receiver. In C, this is easy to implement because native integer types are fixed size and in binary format, so you can just say something like:

uint16_t bytes_to_receive;
recv(sock, &bytes_to_receive, sizeof(bytes_to_receive), 0);
bytes_to_receive = ntohs(bytes_to_receive);
// Now receive 'bytes_to_receive' bytes...

But how is this sort of idiom accomplished using Python sockets? In Python, integers are objects and pickled integers are variable length byte arrays. So we can't use a pickled integer as a length header field, because we can't be sure of its size in bytes.

Of course, I could always send a byte array of known size containing a binary integer, like b'\x05\x00' to create a 16-bit binary integer with a value of 5 in little endian format, but this really doesn't seem like the right approach.

So, how is this usually accomplished in Python?

like image 335
Channel72 Avatar asked Mar 21 '11 16:03

Channel72


People also ask

What is socket recv python?

The recv method receives up to buffersize bytes from the socket. When no data is available, it blocks until at least one byte is available or until the remote end is closed. When the remote end is closed and all data is read, it returns an empty byte string.

What does the socket accept () method return?

RETURN VALUE Upon successful completion, accept() shall return the non-negative file descriptor of the accepted socket. Otherwise, -1 shall be returned and errno set to indicate the error.

What is Af_inet in socket programming?

This address family provides interprocess communication between processes that run on the same system or on different systems. Addresses for AF_INET sockets are IP addresses and port numbers. You can specify an IP address for an AF_INET socket either as an IP address (such as 130.99.


1 Answers

You can use the struct module convert Python integers to and from strings/byte arrays. Just read the number of bytes that correspond to the size of the type header and convert it with the struct module and you should be good to go. (note: be sure to use the right endian-flags when encoding/decoding)

like image 146
Rakis Avatar answered Oct 14 '22 11:10

Rakis