Skip to content

Commit d87d1d7

Browse files
committed
Added timeout option
1 parent 9d35261 commit d87d1d7

File tree

3 files changed

+20
-7
lines changed

3 files changed

+20
-7
lines changed

client/tcpunch.cpp

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,9 +67,12 @@ void* peer_listen(void* p) {
6767
}
6868
}
6969

70-
int pair(const std::string& pairing_name, const std::string& server_address, int port) {
70+
int pair(const std::string& pairing_name, const std::string& server_address, int port, int timeout_ms) {
7171
connection_established = false;
7272
accepting_socket = -1;
73+
struct timeval timeout;
74+
timeout.tv_sec = timeout_ms / 1000;
75+
timeout.tv_usec = (timeout_ms % 1000) * 1000;
7376

7477
int socket_rendezvous;
7578
struct sockaddr_in server_data{};
@@ -85,6 +88,10 @@ int pair(const std::string& pairing_name, const std::string& server_address, int
8588
setsockopt(socket_rendezvous, SOL_SOCKET, SO_REUSEPORT, &enable_flag, sizeof(int)) < 0) {
8689
error_exit_errno("Setting REUSE options failed: ");
8790
}
91+
if (setsockopt(socket_rendezvous, SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeout, sizeof timeout) < 0 ||
92+
setsockopt(socket_rendezvous, SOL_SOCKET, SO_REUSEPORT, &enable_flag, sizeof(int)) < 0) {
93+
error_exit_errno("Setting timeout failed: ");
94+
}
8895

8996
server_data.sin_family = AF_INET;
9097
server_data.sin_addr.s_addr = inet_addr(server_address.c_str());

client/tcpunch.h

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,12 @@
55
#include <sys/socket.h>
66
#include <cstring>
77
#include <arpa/inet.h>
8+
#include <exception>
89

910
#define DEBUG 0
10-
static const int MAX_RECV_BUFFER = 2048;
1111

12+
struct Timeout : public std::exception {};
1213

13-
int pair(const std::string& pairing_name, const std::string& server_address, int port = 10000);
14+
int pair(const std::string& pairing_name, const std::string& server_address, int port = 10000, int timeout_ms = 0);
1415

1516
#endif

common/utils.h

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,20 +2,25 @@
22
#define HOLEPUNCHINGSERVERCLIENT_UTILS_H
33

44
#include <arpa/inet.h>
5+
#include <exception>
6+
#include "../client/tcpunch.h"
57

68
typedef struct {
79
struct in_addr ip;
810
in_port_t port;
911
} PeerConnectionData;
1012

1113
void error_exit(const std::string& error_string) {
12-
std::cerr << error_string << std::endl;
13-
exit(EXIT_FAILURE);
14+
throw error_string;
1415
}
1516

1617
void error_exit_errno(const std::string& error_string) {
17-
std::cerr << error_string << strerror(errno) << std::endl;
18-
exit(EXIT_FAILURE);
18+
if (errno == EAGAIN) {
19+
throw Timeout();
20+
} else {
21+
std::string err = error_string + strerror(errno);
22+
throw err;
23+
}
1924
}
2025

2126
std::string ip_to_string(in_addr_t *ip) {

0 commit comments

Comments
 (0)