How to resolve “Address already in use” error with bind system call
In Category C/C++ Networking
To get rid of “Address already in use” error with bind system call, SO_REUSEADDR socket option should be set before invoking bind. This makes operating system to allow the socket to bind if there is no active socket bound to the requested address and port. Add the following code to the code snippet provided in “Find peer IP address and port number using getpeername” article.
/* create a socket */
sd = socket(AF_INET,SOCK_STREAM,0);
opt = 1;
if(setsockopt (sd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof (opt)) < 0) {
perror("setsockopt");
exit(1);
}
...
Recent Comments