Skip to content

Commit

Permalink
Merge pull request #181 from flaviojs/warn-SO_REUSEADDR-not-set
Browse files Browse the repository at this point in the history
Warn when SO_REUSEADDR is not set.
  • Loading branch information
grossmj authored Apr 3, 2024
2 parents 657f314 + c94f4cf commit 40a1618
Showing 1 changed file with 14 additions and 5 deletions.
19 changes: 14 additions & 5 deletions common/net.c
Original file line number Diff line number Diff line change
Expand Up @@ -331,10 +331,14 @@ int udp_connect(int local_port,char *remote_host,int remote_port)
}

/* try to connect to remote host */
setsockopt(sck, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
if (setsockopt(sck, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)) != 0)
perror("Warning: upd_connect: setsockopt(SO_REUSEADDR)");

if (!bind(sck,(struct sockaddr *)&st,res->ai_addrlen) &&
!connect(sck,res->ai_addr,res->ai_addrlen))
!connect(sck,res->ai_addr,res->ai_addrlen)) {
perror("udp_connect: bind/connect");
break;
}

close(sck);
sck = -1;
Expand Down Expand Up @@ -375,7 +379,9 @@ int udp_connect(int local_port,char *remote_host,int remote_port)
sin.sin_family = PF_INET;
sin.sin_port = htons(local_port);

setsockopt(sck, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
if (setsockopt(sck, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)) != 0)
perror("Warning: upd_connect: setsockopt(SO_REUSEADDR)");

if (bind(sck,(struct sockaddr *)&sin,sizeof(sin)) < 0) {
perror("udp_connect: bind");
close(sck);
Expand Down Expand Up @@ -438,11 +444,13 @@ int ip_listen(char *ip_addr,int port,int sock_type,int max_fd,int fd_array[])
if (fd_array[nsock] < 0)
continue;

setsockopt(fd_array[nsock],SOL_SOCKET,SO_REUSEADDR,&reuse,sizeof(reuse));
if (setsockopt(fd_array[nsock],SOL_SOCKET,SO_REUSEADDR,&reuse,sizeof(reuse)) != 0)
perror("Warning: ip_listen: setsockopt(SO_REUSEADDR): The same address-port combination can be retried after the TCP TIME_WAIT state expires.");

if ((bind(fd_array[nsock],res->ai_addr,res->ai_addrlen) < 0) ||
((sock_type == SOCK_STREAM) && (listen(fd_array[nsock],5) < 0)))
{
perror("ip_listen: bind/listen");
close(fd_array[nsock]);
fd_array[nsock] = -1;
continue;
Expand Down Expand Up @@ -477,7 +485,8 @@ int ip_listen(char *ip_addr,int port,int sock_type,int max_fd,int fd_array[])
if (ip_addr && strlen(ip_addr))
sin.sin_addr.s_addr = inet_addr(ip_addr);

setsockopt(sck,SOL_SOCKET,SO_REUSEADDR,&reuse,sizeof(reuse));
if (setsockopt(sck,SOL_SOCKET,SO_REUSEADDR,&reuse,sizeof(reuse)) != 0)
perror("Warning: ip_listen: setsockopt(SO_REUSEADDR): The same address-port combination can be retried after the TCP TIME_WAIT state expires.");

if (bind(sck,(struct sockaddr *)&sin,sizeof(sin)) < 0) {
perror("ip_listen: bind");
Expand Down

0 comments on commit 40a1618

Please sign in to comment.