I have a project in JAVA, in which i bind tcp sockets in specific ports.
When i call the close() method for a socket bind on port X, i cannot bind a new socket on port X for a few seconds, although i have called the close() method. But after a few seconds it is ok to bind.
Is this normal to be happening? Or should I check my code again?
That’s the problem right there, and the solution is not to do it. Let the system choose.
Binding to specific local ports isn’t a solution to anything, at least not to anything sane. Occasionally overenthusiastic netadmins specify outbound port ranges in the mistaken belief or delusion that (a) it adds to security and (b) it is easily implementable. Neither is correct.
The TIME_WAIT state isn’t ‘the OS [taking] a while to be informed’, it is an essential security feature of TCP. Closed sockets linger for a couple of minutes. Unless you are binding to specific local outbound ports this is a feature, not a bug.