What would cause a TCP socket to throw "java.net.BindException: Address already in use" even when reuse address is set to true? This only occurs if the application is quickly restarted. Running on CentOS 5 linux OS.
-
3Are you making sure to close the TCP socket correctly? How are you restarting the application?AlbertoPL– AlbertoPL2009-05-11 05:54:43 +00:00Commented May 11, 2009 at 5:54
-
Something else is using that port. What exactly is the sequence of events when the application is restarted?Jeremy Huiskamp– Jeremy Huiskamp2009-05-11 05:56:00 +00:00Commented May 11, 2009 at 5:56
-
It's a hard restart of the application terminated by another "software monitor" application. (Lets just assume its a pkill).Michael– Michael2009-05-11 06:23:36 +00:00Commented May 11, 2009 at 6:23
-
I have seen the same thing with .NET on Windows, if a sever process was "killed" instead of shut down normally.Matt Solnit– Matt Solnit2009-05-22 19:05:34 +00:00Commented May 22, 2009 at 19:05
-
Make that "server", not "sever" :-)Matt Solnit– Matt Solnit2009-05-22 19:06:01 +00:00Commented May 22, 2009 at 19:06
3 Answers
This kinda explains it:
http://www.beej.us/guide/bgnet/output/html/singlepage/bgnet.html#bind
Sometimes, you might notice, you try to rerun a server and bind() fails, claiming "Address already in use." What does that mean? Well, a little bit of a socket that was connected is still hanging around in the kernel, and it's hogging the port. You can either wait for it to clear (a minute or so), or add code to your program allowing it to reuse the port, like this
(provides C code)
Basically, in C, you call a function called setsockopt(), and one of the parameters is called SO_REUSEADDR, which lets you reuse that port.
I found some brief links on google which should get you started figuring out how to set the equivalent option in Java:
http://java.sun.com/j2se/1.4.2/docs/guide/net/socketOpt.html
http://java.sun.com/j2se/1.4.2/docs/api/java/net/SocketOptions.html