Address already in use error

Hi Guys,

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.

Thanks
You need to call setsockopt(s, SOL_SOCKET, SO_REUSEADDR, ... immediately after creating the socket with int s = socket(AF_INET, ...

It seems you're already doing that, so I'm not sure what's wrong.
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.
SO_REUSEADDR is supposed to allow the waiting socket to be reused, so you don't have to wait for it to be released.

The danger is, of course, that's you can receive pending data from the previous session.

It's not clear what's been done between calling socket and setsockopt. If there's nothing between them, then I'm stumped too.
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.

Thanks
Last edited on
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?
Yeah... it's quite strange. But could you provide us the output of uname -a. Also full listing of your source may be useful.
Ah. You are right jsmith, it does shows that port in use. So I guess there is no way around it. Can I write some script to kill it?
Last edited on
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.
Thanks a lot jsmith.
Topic archived. No new replies allowed.