Cross-platform socket.getsockopt and struct.unpack (or socket timeout)?

Heikki Toivonen hjtoi-better-remove-when_replying at comcast.net
Tue Sep 16 03:24:18 EDT 2008


M2Crypto has some old code that gets and sets socket timeouts in 
http://svn.osafoundation.org/m2crypto/trunk/M2Crypto/SSL/Connection.py, 
for example:

def get_socket_read_timeout(self):
         return 
timeout.struct_to_timeout(self.socket.getsockopt(socket.SOL_SOCKET, 
socket.SO_RCVTIMEO, timeout.struct_size()))

The helper timeout module is here: 
http://svn.osafoundation.org/m2crypto/trunk/M2Crypto/SSL/timeout.py

I just noticed that this does not work on Windows. Here's a small test 
program that demonstrates the issue using native and Cygwin Python 
2.5.2, 32-bit Windows XP (no M2Crypto needed for this):

import struct
import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
timeout_struct = s.getsockopt(socket.SOL_SOCKET, socket.SO_RCVTIMEO, 
struct.calcsize('ll'))
print "%d:'%s'" % (len(timeout_struct), timeout_struct)
print struct.unpack('ll', timeout_struct)

This outputs

4:'    '
Traceback (most recent call last):
   File "t.py", line 8, in <module>
     print struct.unpack('ll', timeout_struct)
   File "/usr/lib/python2.5/struct.py", line 87, in unpack
     return o.unpack(s)
struct.error: unpack requires a string argument of length 8

It works fine on 32 and 64 bit Linux (Ubuntu 8.04).

The kicker is that I can't remember if I actually ever tested this on 
Windows before.

This goes to a level of socket programming that I haven't done before.

Is there a cross-platform way of doing what the M2Crypto code is 
attempting to do?

-- 
   Heikki Toivonen



More information about the Python-list mailing list