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?
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.
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.
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.
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With