Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't socket.close() free up the bound port?

Tags:

java

sockets

I am sending a single message to a TCP server and after running it once I get java.net.BindException: Address already in use errors when I try to run it again. I figured that the socket would be unbound; I can't find anything specifically saying that it does in the documentation, though. How do I free up the port, am I not ending the transaction properly here? Here is my client:

public class TcpPingClient {
   public static void main(String[] args) throws Exception {
      Socket tcpSocket = new Socket();
      tcpSocket.bind(new InetSocketAddress("192.168.1.2", 45030));
      tcpSocket.connect(new InetSocketAddress("192.168.1.2", 1211));
      DataOutputStream out = new DataOutputStream(tcpSocket.getOutputStream());
      out.writeBytes("oh hey\n");
      tcpSocket.close();
   }
}
like image 312
alh Avatar asked Dec 08 '22 12:12

alh


1 Answers

It is unbound, but waiting for timeout in case the other end need some data buffered on the senders end. If you want to re-use a port without waiting for this to happen you can use

socket.setReuseAddress(true);

This must be set before you attempt to bind.

In short, this is how TCP is implemented, not a feature of Java.

like image 173
Peter Lawrey Avatar answered Dec 11 '22 09:12

Peter Lawrey