MOHAMED
MOHAMED

Reputation: 43518

How I can check if a port is in TIME_WAIT status or already taken by another application

I developed a service which contains a tcp server.

When I restart my application, sometime my application is unable to bind the port for the TIME_WAIT reason.

In my application I want to add a procedure when the bind fails. this procedure should check at the beginning the type of the bind fails:

  1. If the reason is due to the TIME_WAIT, then wait amoment and retry again.
  2. If the reason is due to that the port is taken by another application, then choose another port and retry the bind

How I can know the type of the bind fails?

NOTE:

  1. I do not want to use SO_REUSEADDR
  2. the bind errno is the same for both type of fails

Upvotes: 1

Views: 1330

Answers (1)

pkill
pkill

Reputation: 29

Firstly, I would use the SO_REUSEADDR sockopt on your listening socket to avoid this situation in the first place. SO_REUSEADDR will allow you to reuse the same socket your TCP server was using previously upon restart because it is still being held open by the operating system.

Secondly, error handling is always a good idea. I encourage you to check the return value of the bind and handle the most likely errno you expect to encounter. You can get an errno list for bind in section 2 of the man page.

$> man -s 2 bind

Finally, the errno for a socket in TIME_WAIT is the same errno as an address in use: EADDRINUSE. This is because a socket in TIME_WAIT is in use by the OS.

Upvotes: 2

Related Questions