I have a code for server using sockets. When I close the server process using Ctrl+C and then try to restart is again, I get bind: address already in use error.
This is getting really frustrating. I have no idea how to fix it. One way I tried is
1 2 3 4 5 6 7 8 9 10 11 12
int optval = 1 ; 58
if (setsockopt(serverSockFd,SOL_SOCKET,SO_REUSEADDR,&optval,si
zeof(int)) == -1) {
perror("setsockopt") ;
exit(-1) ;
}
bind(...); // bind code continued
It still does not work. I am not sure if I am placing setsockopt at wrong place.
Any guidance on solving this error would be very helpful.
If you've run your program without the setsockopt() call and have not rebooted or waited long enough,
the address will still be in use from that run. Otherwise I am 100% sure your setsockopt call is at the
right place and is correct.
Thanks for the reply guys. I even tried it putting just after socket() call. It still gives that same annoying error. I have no idea what's going on. T_T
Edit: jsmith: Am I supposed to wait even with setsockopt()? Actually, like kbw said, I thought that after using setsockopt() we do not have to wait. I works even without setsockopt(), if I wait. But that's the whole point that I do not want to wait. :-(
Please let me know any other approach that I can take to avoid this.
No. Let me clarify. Using the SO_REUSEADDR option tells the kernel that when the socket is closed, the port
bound to the socket should be freed immediately rather than kept in-use for some period of time.
It does not provide a means by which the user can bind an already in-use port to the socket by first reclaiming
the port number.
What does netstat -a show? Does it show the port in use?
If it's in use by a currently running process, then you'll have to kill the process. There is no way to force a
running process to give up the port. Otherwise, you'll likely have to reboot if the port has been in use
for days.