diff --git a/Changelog b/Changelog index c674405..319d98e 100644 --- a/Changelog +++ b/Changelog @@ -1,4 +1,5 @@ 2019-03-04: +- added: TCP connections have set up a timeout of 2 seconds. - fixed: TCP connect set up the sock struct too fast so threaded applications had some problem if the connect went into a time out. diff --git a/tcp.cc b/tcp.cc index 9d0fcef..f92a3a7 100644 --- a/tcp.cc +++ b/tcp.cc @@ -160,6 +160,7 @@ int TCP::Connect(string hostport, int defaultport) { int TCP::Connect() { int err, s; struct addrinfo hints, *res, *rp; + struct timeval timeout; memset(&hints, 0, sizeof(struct addrinfo)); hints.ai_family = AF_UNSPEC; // use IPv4 or IPv6 @@ -178,6 +179,12 @@ int TCP::Connect() { // for (rp = res; rp != NULL; rp = rp->ai_next) { s = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol); + + // setup timeout to max 2 secs + timeout.tv_sec = 2; + timeout.tv_usec = 0; + setsockopt(s, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout)); + if (s == -1) continue; if (connect(s, rp->ai_addr, rp->ai_addrlen) != -1) { sock = s;