How to set keep-alive timer in python 2.5 running in Windows 7

橙三吉。 提交于 2019-12-11 08:54:40

问题


I need some help. I'm working on a legacy software that uses python 2.5.4 running on Windows7 and I need to enable keepalives in my socket connection.

I've seen in the thread below that you can enable keepalives in python using

object.setsockopt( socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)

However this setup uses the default windows keep alive timer of 2 hours.

I've also seen that we can set the timer using the following API, however it is only available for Python 2.6 onwards.

sock.ioctl(socket.SIO_KEEPALIVE_VALS, (1, 10000, 3000))

Is there anyway I can set this SIO_KEEPALIVE_VALS using python 2.5.4 ? The legacy code I have also has the module pywin32-214. I really can't upgrade the python version.

I also wonder how python2.6 and newer calls the windows api

int WSAIoctl(
  (socket) s,              // descriptor identifying a socket
  SIO_KEEPALIVE_VALS,                  // dwIoControlCode
  (LPVOID) lpvInBuffer,    // pointer to tcp_keepalive struct 
  (DWORD) cbInBuffer,      // length of input buffer 
  NULL,         // output buffer
  0,       // size of output buffer
  (LPDWORD) lpcbBytesReturned,    // number of bytes returned
  (LPWSAOVERLAPPED) lpOverlapped,   // OVERLAPPED structure
  (LPWSAOVERLAPPED_COMPLETION_ROUTINE) lpCompletionRoutine,  // completion routine
);

Thanks for your help.

References: How to change tcp keepalive timer using python script?

https://msdn.microsoft.com/en-us/library/dd877220%28v=vs.85%29.aspx


回答1:


Here is how you do it in c

static PyObject*
sock_ioctl(PyObject *argO , PyObject *arg)
{
PyObject *s;
DWORD recv;
struct tcp_keepalive ka;
if (!PyArg_ParseTuple(arg, "O(kkk):keepalive",&s,
    &ka.onoff, &ka.keepalivetime, &ka.keepaliveinterval))
    return NULL;

if (WSAIoctl(PyObject_AsFileDescriptor(s), SIO_KEEPALIVE_VALS, &ka,  sizeof(ka),
    NULL, 0, &recv, NULL, NULL) == SOCKET_ERROR) {
    return set_error();
}
return PyLong_FromUnsignedLong(recv);
}

I made a small python extension in github https://github.com/rawinput/ioctl compiled for python 2.5



来源:https://stackoverflow.com/questions/40779973/how-to-set-keep-alive-timer-in-python-2-5-running-in-windows-7

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!