Winsock – Windows Sockets API

Posted by JSmith on Sep 10, 2025

I'm trying to debug a socket connection that seems to hang after connect(). I suspect it might be related to the TCP keep‑alive settings, but I'm not sure how to configure them correctly in Winsock.

Has anyone faced a similar issue or can point me to the right documentation?

You can set the keep‑alive interval with setsockopt() using TCP_KEEPIDLE, TCP_KEEPINTVL, and TCP_KEEPCNT. Here's a quick example:

int opt = 1;
setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, (char *)&opt, sizeof(opt));
int idle = 60; // seconds
setsockopt(s, IPPROTO_TCP, TCP_KEEPIDLE, (char *)&idle, sizeof(idle));
int interval = 10;
setsockopt(s, IPPROTO_TCP, TCP_KEEPINTVL, (char *)&interval, sizeof(interval));
int cnt = 5;
setsockopt(s, IPPROTO_TCP, TCP_KEEPCNT, (char *)&cnt, sizeof(cnt));

Make sure you include Ws2tcpip.h and link against Ws2_32.lib.

Also, check that the firewall isn’t blocking outbound traffic on the port you’re using. Sometimes the OS will silently drop packets if the rule isn’t set correctly.


Leave a comment