Monthly Archives: October 2008

Fun with Sockets

Whilst doing some coding today for my semester research project I found a need to check for incoming data on a socket without taking any data out of the stream. Here’s the code I came up with:

 cp.sock.setblocking(False) try: cp.sock.recv(0) stuffwaiting = True except socket.error: stuffwaiting = False cp.sock.setblocking(True) 

This code works finely on Linux — you can only receive data if there is data to be received (even if you want to receive no data). Unfortunately, the code doesn’t port to Mac OS — you may receive as many bytes as there are in the socket’s buffer — if there are no bytes in the buffer, you can receive 0 bytes. Therefore, the following fix is necessary:

 cp.sock.setblocking(False) try: cp.sock.recv(1, socket.MSG_PEEK) stuffwaiting = True except socket.error: stuffwaiting = False cp.sock.setblocking(True) 

So, my question for Lazyweb is: is there a better way to do this?