Reputation: 1091
I am getting BindException exception while reusing same Address.Following is my code.
in openConnection method :
69. Selector selector = SelectorProvider.provider().openSelector();
70. SocketChannel socketChannel = SocketChannel.open();
71. socketChannel.bind(new InetSocketAddress(port));// Edited
72. socketChannel.socket().setReuseAddress(true);
73. socketChannel.configureBlocking(false);
74. socketChannel.connect(remoteAddress);
Exception:
java.net.BindException: Address already in use
at sun.nio.ch.Net.bind0(Native Method)
at sun.nio.ch.Net.bind(Net.java:414)
at sun.nio.ch.Net.bind(Net.java:406)
at sun.nio.ch.SocketChannelImpl.bind(SocketChannelImpl.java:580)
at sun.nio.ch.SocketAdaptor.bind(SocketAdaptor.java:135)
at com.example.client.request.Client.openConnection(Client.java:72)
Edit
I solved InvalidArgument exception and I have edited the post above but now while reconnecting on same port I get the above exception.Is some thing I am doing wrong?
Upvotes: 1
Views: 2414
Reputation: 3367
If you want to reuse an address you have to call setReuseAddress(true) before binding the socket.
Upvotes: 2
Reputation: 151
Signals that an error occurred while attempting to bind a socket to a local address and port. Typically, the port is in use, or the requested local address could not be assigned.
When you start a web server or application server, which typically listen on a port e.g. Tomcat or Jetty listens on 8080 and 8084 for HTTP and HTTPS traffic, they bind a socket to a local address and port. If you give them hostname e.g. localhost or devhost, then they used /etc/host in both Windows and Linux to resolve domain name into IP address, if this mapping is incorrect than you will get java.net.BindException: Cannot assign requested address: JVM_Bind. This host to IP address mapping file can be found at C:\Windows\System32\Drivers\etc\hosts, where C:\Windows is where you have installed windows operating system. If you look at this file, you will see it contains IP address and hostname as shown below :
192.168.52.1 localhost
Just, correct the mapping, or add 127.0.0.1 against localhost to resolve this issue
Upvotes: 1