java.net.BindException: Address already in use while re using same connection - java

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?

If you want to reuse an address you have to call setReuseAddress(true) before binding the socket.

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 :
127.0.0.1 localhost
192.168.52.1 localhost
Just, correct the mapping, or add 127.0.0.1 against localhost to resolve this issue

Related

java.net.SocketException: Unresolved address

I have implemented a server application in Java that I am trying to deploy in the cloud. I have a problem with this part of the code
serverSocket = ServerSocketChannel.open();
serverSocket.socket().bind(new InetSocketAddress(myHost,myPort));
When I set String myHost = "localhost", everything works fine. However, I would like to it to work with the public Ip of the remote machine. I have tried 2 different things
String myHost = "10.0.0.4" (the Ip I get when running ifconfig). In that case I get
java.net.BindException: Cannot assign requested address
at sun.nio.ch.Net.bind0(Native Method)
at sun.nio.ch.Net.bind(Net.java:433)
at sun.nio.ch.Net.bind(Net.java:425)
at sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:223)
at sun.nio.ch.ServerSocketAdaptor.bind(ServerSocketAdaptor.java:74)
at sun.nio.ch.ServerSocketAdaptor.bind(ServerSocketAdaptor.java:67)
String myHost = "publichost", and I add a line 10.0.0.4 publichost to my /etc/hosts/ file. In that case I get
java.net.SocketException: Unresolved address
at sun.nio.ch.Net.translateToSocketException(Net.java:131)
at sun.nio.ch.Net.translateException(Net.java:157)
at sun.nio.ch.Net.translateException(Net.java:163)
at sun.nio.ch.ServerSocketAdaptor.bind(ServerSocketAdaptor.java:76)
at sun.nio.ch.ServerSocketAdaptor.bind(ServerSocketAdaptor.java:67)
What I am doing wrong?
The first error (typically) means that you are binding to an IP + port combination that is already in use.
Use netstat -lntp to list all of the programs listening on a tcp port, and look for the port you are trying to use. Then either shutdown the program ... or pick a different port.
It might also mean that you are using the wrong IP entirely. When you call bind on a server socket, the address and port should be the IP and port on which your application expects to receive incoming connections. So the IP must be an IP for this host (NOT the remote host). Note that you can also use 0.0.0.0 ... which means "all IP addresses for this host".
The second error could mean:
Your DNS resolver is not looking at your "/etc/hosts" file.
The /etc/hosts entry is incorrect; you are supposed to put the fully qualified name for your host into the entry; see Fully qualified machine name Java with /etc/hosts
Something else.
But I suspect that if you fixed the "Unresolved address" problem without fixing the cause of the original "Cannot assign requested address", the latter would reappear. You shouldn't need a DNS entry to bind a server socket!

make_sock: could not bind to address 0.0.0.0:80

One of the suggested solutions is to note the PID running on port 80 (netstat -ano), kill it and start Apache and this has solved problem for many others. But for me Apache itself is running on port 80 and when I start the service I get socket not available error.
I tried changing the port to 8080 or other but no luck. Please suggest me where I am going wrong?
Exact Error Msg:
C:\Program Files (x86)\Apache Software Foundation\Apache2.2\bin>httpd.exe
(OS 10048)Only one usage of each socket address (protocol/network address/port)
is normally permitted. : make_sock: could not bind to address 0.0.0.0:80
no listening sockets available, shutting down
Unable to open logs
There is no such address as 0.0.0.0; if you are trying to bind to an Apache port on the local host, use 127.0.0.1, please.

netty bootstrap connection refused

trying to connect client io.netty.bootstrap.Bootstrap:
ChannelFuture cf = null;
cf = m_bootstrap.connect(new InetSocketAddress(InetAddress
.getByName("127.0.0.1"), 8084));
in cf, result : java.net.ConnectException: Connection refused: /127.0.0.1:8084
detailed message:
[sun.nio.ch.SocketChannelImpl.checkConnect(Native Method),
sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:599),
io.netty.channel.socket.nio.NioSocketChannel.doFinishConnect(NioSocketChannel.java:208),
io.netty.channel.nio.AbstractNioChannel$AbstractNioUnsafe.finishConnect(AbstractNioChannel.java:287),
io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:528),
io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:468),
io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:382),
io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:354),
io.netty.util.concurrent.SingleThreadEventExecutor$2.run(SingleThreadEventExecutor.java:116),
java.lang.Thread.run(Thread.java:695)]
my /etc/hosts file looks like this:
127.0.0.1>--localhost
255.255.255.255>broadcasthost
::1 localhost-
****::1%lo*>localhost
127.0.0.1>--********
Not sure what to do? literally assumed I can pass localhost and port and it should work.
Are you sure there is something really listing on the port ?
Try:
telnet 127.0.0.1 8084
turns out in MAC since the server binds to my IP address and not localhost or 127.0.0.1 it would not accept the the client to connect to localhost/127.0.0.1.
It worked fine when I replaced loopback addr with my IP. Strange but guess it is something to do with difference interfaces in MAC. Not sure how Windows would react.

Why does java rmi keep connecting to 127.0.1.1. When ip is 192.168.X.X?

I have a java rmi application i simply do:
Client:
Registry registry = LocateRegistry.getRegistry("localhost");
costApi = (CostApi) registry.lookup("server.CostApi");
Everything works fine when I host the server at localhost. When I start the same program at another machine withing the local network, at 192.168.x.x and change to:
Client:
Registry registry = LocateRegistry.getRegistry("192.168.x.x");
costApi = (CostApi) registry.lookup("server.CostApi");
it does not work anymore and it fails with a very strange error:
java.rmi.ConnectException: Connection refused to host: 127.0.1.1; nested exception is:
java.net.ConnectException: Connection refused
at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:619)
at sun.rmi.transport.tcp.TCPChannel.createConnection(TCPChannel.java:216)
at sun.rmi.transport.tcp.TCPChannel.newConnection(TCPChannel.java:202)
at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:129)
at java.rmi.server.RemoteObjectInvocationHandler.invokeRemoteMethod(RemoteObjectInvocationHandler.java:194)
at java.rmi.server.RemoteObjectInvocationHandler.invoke(RemoteObjectInvocationHandler.java:148)
at com.sun.proxy.$Proxy0.dataCost(Unknown Source)
at billing.data.DataBiller.performBilling(DataBiller.java:57)
at billing.data.DataBiller.consumeMessage(DataBiller.java:46)
at general.templates.RabbitWorker.run(RabbitWorker.java:124)
at java.lang.Thread.run(Thread.java:744)
Caused by: java.net.ConnectException: Connection refused
at java.net.PlainSocketImpl.socketConnect(Native Method)
I'm not even trying to connect to 127.0.1.1 but to 192.168.x.x, how do I solve this? I prefer to use java code only and not modify my machine with config files. I'm using linux
This is usually caused by a misconfiguration. Check your /etc/hosts file to ensure that:
localhost maps to 127.0.0.1
your real hostname maps to your real host address
Some Linux distributions are known to have this back to front.
If the problem persists, try setting java.rmi.server.hostname at the server to the IP address the client should use when executing remote method calls. It needs to be set before you export any remote objects, including the Registry.
The problem is caused by the IP address embedded in the stub, which ultimately comes from something like InetAddress.getLocalAddress(), which is fallible as above. It is overridden by java.rmi.server.hostname.
This is item A.1 in the FMI FAQ, but note that the item is mistitled. It doesn't happen during lookup(), it happens when you call a remote method on the resulting stub.
I just ran into the same issue. I'm doing something very similar to what you are doing. What I noticed was that the first time I ran the client program, and it failed ( by design of the firewall test ) - that it failed with an error message showing the actual ip address of the host that I originally specified ( the 192.168.x.x address ), but all subsequent failures show that it is failing to make a connection to 127.0.0.1. Currently I'm suspecting some kind of caching on the client - has the JVM marked that ip address as never accessible again and it's refusing to ever try to connect to it again?
UPDATE: In my case, the JVM on the RMI Server side was not able to properly set the java.rmi.server.hostname property at JVM startup. This property was being left as null. When clients connect to a specific RMI Registry and ask for a stub to a particular named object, they receive a stub containing the ip address of the remote machine where the actual object can be found. The RMI server copies the contents of the java.rmi.server.hostname property into the stubs it returns to clients, so if the java.rmi.server.hostname property is "" and it copies that to each stub it creates, each stub contains a reference to remote server with an IP address of "". By default the client jvm reacts to this by attempting to connect to the server object on the localhost, 127.0.0.1. To work around the problem, try this line of code before exporting any remote objects on the server side:
System.setProperty( "java.rmi.server.hostname", "192.168.RMIServer.IP" ) ;
This property will be automatically copied to all remote stubs exported on that server, and clients who receive that stub should then be able to reach the remote server ( assuming any firewalls are configured correctly ).

java.net.UnknownHostException: Invalid hostname for server: local

What are the steps I should take to solve the error:
java.net.UnknownHostException: Invalid hostname for server: local
I added the new virtual host name at Android emulator but the result returns to
java.net.UnknownHostException virtualhostname at
java.net.InetAddress.lookUpHostByName(InetAddress.java:506)
When I type my virtualhost URL on my PC, it works on display. Then again, when I ran on Emulator and check on Logcat, I couldn't be able to read or check the HTTP status if 200, 202, or an error code number. It simply returned to UnknownHostException
I was having the same issue on my mac. I found the issue when I pinged my $HOSTNAME from terminal and it returned ping: cannot resolve myHostName: Unknown host.
To resolve:
Do echo $HOSTNAME on your terminal.
Whatever hostname it shows (lets say myHostName), try to ping it : ping myHostName. If it returns ping: cannot resolve myHostName: Unknown host then add an entry into your /etc/hosts file.
For that edit /etc/hosts file and add following:
127.0.0.1 myHostName
What the exception is really saying is that there is no known server with the name "local". My guess is that you're trying to connect to your local computer. Try with the hostname "localhost" instead, or perhaps 127.0.0.1 or ::1 (the last one is IPv6).
From the javadocs:
Thrown to indicate that the IP address
of a host could not be determined.
127.0.0.1or ::1 or "localhost" should always be the loopback interface, so if that doesn't work I'd be really surprised.
If there really is a server called "local" on your network - examine your DNS settings or add it to your hosts file.
java.net.UnknownHostException: Host is unresolved:
Thrown to indicate that the IP address of a host could not be determined.
This exception is also raised when you are connected to a valid wifi but router does not receive the internet. Its very easy to reproduce this:
Connect to a valid wifi
Now remove the cable from the router while router is pluged-in
You will observe this error!!
You can't really solve this, You can only notify the user gracefully. (something like - "Unable to make a connection")
This is not specific to the question, but this question showed up when I was Googling for the mentioned UnknownHostException, and the fix is not found anywhere else so I thought I'd add an answer here.
The exception that was continuously received was:
java.net.UnknownHostException: google.com
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:184)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at java.net.Socket.connect(Socket.java:538)
at java.net.Socket.<init>(Socket.java:434)
at java.net.Socket.<init>(Socket.java:211)
...
No matter how I tried to connect to any valid host, printing it in the terminal would not help either. Everything was right.
The Solution
Not calling trim() for the host string which contained whitespace. In writing a proxy server the host was obtained from HTTP headers with the use of split(":") by semicolons for the HOST header. This left whitespace, and causes the UnknownHostException as a host with whitespace is not a valid host. Doing a host = host.trim() on the String host solved the ambiguous issue.
Your hostname is missing. JBoss uses this environment variable ($HOSTNAME) when it connects to the server.
[root#xyz ~]# echo $HOSTNAME
xyz
[root#xyz ~]# ping $HOSTNAME
ping: unknown host xyz
[root#xyz ~]# hostname -f
hostname: Unknown host
There are dozens of things that can cause this. Please comment if you discover a new reason.
For a hack until you can permanently resolve this issue on your server, you can add a line to the end of your /etc/hosts file:
127.0.0.1 xyz.xxx.xxx.edu xyz
This might happen due to various reasons
1) Check if you have VPN connected, you might get this error sometimes if yes
"Your hostname, localhost resolves to a loopback address: 127.0.0.1; using 10.xxx.1.193 instead (on interface cscotun0)"
2) Check your $HOSTNAME
3) try to ping $HOSTNAME on commandline and if it doesnt work, tweak the system settings to make your local host respond to pings
Try the following :
String url = "http://www.google.com/search?q=java";
URL urlObj = (URL)new URL(url.trim());
HttpURLConnection httpConn =
(HttpURLConnection)urlObj.openConnection();
httpConn.setRequestMethod("GET");
Integer rescode = httpConn.getResponseCode();
System.out.println(rescode);
Trim() the URL
Trying to connect to your local computer.try with the hostname "localhost" instead or perhaps ::/ - the last one is ipv6
Please try to set SPARK_LOCAL_IP environment variable to the ip address(can be localhost i.e. your own ip address) you want to connect. E.g.
$ export SPARK_LOCAL_IP=182.95.208.152
This way you will not be required to alter existing linux settings.
Worked for me, hope helps you too.
Connect your mobile with different wifi connection with different service provider.
I don't know the exact issue but i could not connect to server with a specific service provider but it work when i connected to other service provider. So try it!
I had this issue in my android app when grabbing an xml file the format of my link was not valid, I reformatted with the full url and it worked.
If you are here because your emulator gives you that Exception, Go to Tools > AVD Manager in your android emulator and Cold boot your Emulator.
I had the same issue.
Restart docker was the fix for me. For some reason it needed a restart, I donĀ“t know why, but it worked.
If your /etc/localhosts file has entry as below:
Add hostname entry as below:
127.0.0.1 local host (add your hostname here)
::1 (add hostname here) (the last one is IPv6).
This should resolve the issue.

Categories