Search code examples
pythonsocketstcptimeout

Python set tcp send timeout


I'm trying to set TCP's SO_SNDTIMEO in Python. Based on the socket documentation here (http://docs.python.org/2/library/socket.html), it seems as though I should use setsockopt.

However, I'm having a difficult time understanding what to pass in for the third value parameter. I'm trying to use the struct module (http://docs.python.org/2/library/struct.html#module-struct), as the documentation recommends. However, I'm not sure what struct I should actually be using to set the option. Anyone have any thoughts?

(I've also tried passing both strings and integers for the third argument.) Thanks!


Solution

  • The underlying C implementation expects a timeval struct, which can be found here. It consists of two long ints, the first of which represents a time in seconds while the second is a time in microseconds.

    According to the struct.pack documentation, you can create a struct with two long fields using the format string ‘ll’, thus the following should set SO_SNDTIMEO as expected:

    timeval = struct.pack('ll', some_num_secs, some_num_microsecs)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_SNDTIMEO, timeval)