0

I am making a Tic Tac Toe application, with client/server. When pressing CTRL+C I have a custom handler that closes the sockets (the listening one as well), and then exits. However, if I try to run the program again, sometimes it gives an error that the port is used so it cannot bind, which lasts from several minutes (or until restart), to some seconds and sometimes it doesn't happen at all. I suspect this is a normal process, however I would like a second opinion. Also, any suggestions on how to avoid this would be appreciated!

EDIT: forgot to mention that, again SOMETIMES, killing the terminal works.

alk
  • 69,737
  • 10
  • 105
  • 255
  • Could you provide a working example? – celicoo Jan 08 '19 at 16:23
  • the code is around 500 lines so I guess you don't mean that. One instance of it happening is, when a player wins for example, both the server and the two clients are killed (sockets closed, processes killed). Sometimes after that I need to wait or restart. – butterflyflyaway Jan 08 '19 at 16:25
  • How do you handle your clients, `threads`, `select()` ...? – Michi Jan 08 '19 at 17:49
  • Are you using `signal()`? -> [What happens if you use it?](https://pastebin.com/raw/2nYxb83m) – Michi Jan 08 '19 at 17:54

1 Answers1

2

There is a connection (identified by IP address and port number) still in TIME_WAIT state. This state exists because there might be some IP packages around in the net that were sent to this connection. You probably get an error EADDRINUSE when you try to bind the socket. You can check this with netstat.

Read about socket option SO_REUSEADDR and SO_REUSEPORT.

related: Socket options SO_REUSEADDR and SO_REUSEPORT, how do they differ? Do they mean the same across all major operating systems?

David Hoelzer
  • 15,862
  • 4
  • 48
  • 67
Bodo
  • 9,287
  • 1
  • 13
  • 29