Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling output of python socket recv

Tags:

python

sockets

Apologies for the noob Python question but I've been stuck on this for far too long.

I'm using python sockets to receive some data from a server. I do this:


data = self.socket.recv(4)
print "data is ", data
print "repr(data) is ", repr(data)

The output on the console is this:

data is
repr(data) is '\x00\x00\x00\x01'

I want to turn this string containing essentially a 4 byte number into an int - or actually what would be a long in C. How can I turn this data object into a numerical value that I can easily manage?

like image 674
chrism1 Avatar asked Mar 27 '09 20:03

chrism1


People also ask

What does recv () return in Python?

RETURN VALUE Upon successful completion, recv() shall return the length of the message in bytes. If no messages are available to be received and the peer has performed an orderly shutdown, recv() shall return 0. Otherwise, -1 shall be returned and errno set to indicate the error.

What does socket recv do 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.

How does socket recv work?

If data is not available for the socket socket, and socket is in blocking mode, the recv() call blocks the caller until data arrives. If data is not available and socket is in nonblocking mode, recv() returns a -1 and sets the error code to EWOULDBLOCK.

What is S RECV 1024?

So, in our client.py , we'll do: msg = s. recv(1024) This means our socket is going to attempt to receive data, in a buffer size of 1024 bytes at a time.


1 Answers

You probably want to use struct.

The code would look something like:

import struct

data = self.socket.recv(4)
print "data is ", data
print "repr(data) is ", repr(data)
myint = struct.unpack("!i", data)[0]
like image 186
grieve Avatar answered Nov 05 '22 05:11

grieve