Linux sockets: Difference between revisions
Jump to navigation
Jump to search
Use
Line 50: | Line 50: | ||
On a server, this is probably due to an old instance of the server that tries to bind to the same port and address [https://stackoverflow.com/questions/15198834/bind-failed-address-already-in-use]. |
On a server, this is probably due to an old instance of the server that tries to bind to the same port and address [https://stackoverflow.com/questions/15198834/bind-failed-address-already-in-use]. |
||
As a fix, try to bind with option <code>SO_REUSEADDR</code> and/or <code>SO_REUSEPORT</code>. |
As a fix, try to bind with option <code>SO_REUSEADDR</code> and/or <code>SO_REUSEPORT</code>. From [https://stackoverflow.com/questions/24194961/how-do-i-use-setsockoptso-reuseaddr SO]: |
||
<source lang="bash"> |
|||
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &(int){ 1 }, sizeof(int)) < 0) |
|||
error("setsockopt(SO_REUSEADDR) failed"); |
|||
</source> |
|||
For more information, see [http://man7.org/linux/man-pages/man7/socket.7.html socket(7)] and [http://man7.org/linux/man-pages/man7/ip.7.html ip(7)] manpages. |
Revision as of 11:45, 17 September 2018
Tutorials
- A thoough step-by-step example of client and socket code.
- Simple example of client and server code using Linux sockets.
References
- A very detailed answer about the differences between
SO_REUSEADDR
andSO_REUSEPORT
.
- A course on internet technologies, including Domain Naming (DNS...), the IP protocol, the TCP protocol, ...
- Manpages:
Troubleshooting
Use errno / strerror to get error
if( bind(socket_desc,(struct sockaddr *)&server , sizeof(server)) < 0)
{
printf("bind failed: %s (errno %d)", strerror(errno), errno);
return 1;
}
Use netstat
to get socket status
./server
# bind done
# Waiting for incoming connections...
# Connection accepted
# Handler assigned
# ^C
./server
# bind failed: Address already in use (errno 98)
netstat -a | grep 8888
# tcp 0 0 zavcxl0005:58888 165.225.76.32:http ESTABLISHED
# tcp 0 0 zavcxl0005:48888 10.75.126.1:https ESTABLISHED
# tcp 0 0 localhost.localdom:8888 localhost.localdo:50310 TIME_WAIT
# ... So port is still in use
bind failed: Address already in use (errno 98)
Call to bind
fails with error
bind failed: Address already in use (errno 98)
On a server, this is probably due to an old instance of the server that tries to bind to the same port and address [1].
As a fix, try to bind with option SO_REUSEADDR
and/or SO_REUSEPORT
. From SO:
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &(int){ 1 }, sizeof(int)) < 0)
error("setsockopt(SO_REUSEADDR) failed");