0

I'm developing a server using Asio on Linux. Whenever the application gets closed by any means (Ctrl+C, stopping the debugger or getting a crash), it looks like I can't launch the server until after one minute or so. I find this very frustrating for iteration times.

This is the error message I get:

bind: Address already in use

I believe it could be that the port keeps open.

What can I do to to avoid having to wait each time? I would imagine there must be some way to handle terminating the program gracefully by closing the port properly. But I would also like to know a solution that works when I stop the program from the debugger or it crashes.

tuket
  • 2,117
  • 1
  • 19
  • 33
  • 1
    Have you tried tracking down what's holding that open with a tool like [`lsof`](https://en.wikipedia.org/wiki/Lsof)? – tadman Nov 02 '19 at 20:31
  • 1
    Have a read of http://www.serverframework.com/asynchronousevents/2011/01/time-wait-and-its-design-implications-for-protocols-and-scalable-servers.html Might explain why you have to wait. – Richard Critten Nov 02 '19 at 20:31
  • @tadman Thank for the tip, I didn't know that tool. It looks like my program does not show up there, even the port I'm using doesn't seem to be there – tuket Nov 02 '19 at 20:50
  • @RichardCritten Thanks for the link. It's a long explanation, but what I understand so far is that the problem is at the TCP layer so I can't do anything about it :S – tuket Nov 02 '19 at 20:54
  • 1
    Have you set [`SO_REUSEADDR`](https://stackoverflow.com/questions/14388706/how-do-so-reuseaddr-and-so-reuseport-differ)? – tadman Nov 02 '19 at 20:54
  • @tadman No, I don't even know what that is. Just reading it now... – tuket Nov 02 '19 at 20:58
  • I think that's what you need to recycle the port faster. – tadman Nov 02 '19 at 21:00
  • @tadman Thanks, I will try that. I have found this link that tells how to do it in Asio: https://stackoverflow.com/questions/34596638/boost-asio-so-reuseport – tuket Nov 02 '19 at 21:02
  • @tuket Good find. When you do get a working solution, might want to self-answer unless this is a duplicate of that question. – tadman Nov 02 '19 at 21:02
  • @tadman Yes, it worked! Thank you, I feel productive again :) Do you know it this is something that I should enable only during debugging, or it it safe for production as well? – tuket Nov 02 '19 at 21:11
  • 1
    It's something that's normally enabled in boilerplate code which is why it didn't occur to me until thinking about your problem some more. – tadman Nov 02 '19 at 21:12
  • 1
    Possible duplicate of [How do I use setsockopt(SO\_REUSEADDR)?](https://stackoverflow.com/q/24194961/608639), [Socket reusing with boost asio](https://stackoverflow.com/q/8433070/608639), etc. – jww Nov 02 '19 at 21:26
  • @jww Those two talk about `SO_REUSEADDR`, in my case is `SO_REUSEPORT` that solved the problem (the link in my previous comment) – tuket Nov 03 '19 at 09:33

0 Answers0