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!
Related
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:128)
at java.rmi.server.RemoteObjectInvocationHandler.invokeRemoteMethod(RemoteObjectInvocationHandler.java:194)
at java.rmi.server.RemoteObjectInvocationHandler.invoke(RemoteObjectInvocationHandler.java:148)
at com.sun.proxy.$Proxy0.notifyMe(Unknown Source)
at CallbackServerImpl.doCallback(CallbackServerImpl.java:149)
at CallbackServerImpl.registerForCallback(CallbackServerImpl.java:70)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:322)
at sun.rmi.transport.Transport$1.run(Transport.java:177)
at sun.rmi.transport.Transport$1.run(Transport.java:174)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.Transport.serviceCall(Transport.java:173)
at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:553)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:808)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:667)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:722)
Caused by: java.net.ConnectException: Connection refused
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:391)
at java.net.Socket.connect(Socket.java:579)
at java.net.Socket.connect(Socket.java:528)
at java.net.Socket.<init>(Socket.java:425)
at java.net.Socket.<init>(Socket.java:208)
at sun.rmi.transport.proxy.RMIDirectSocketFactory.createSocket(RMIDirectSocketFactory.java:40)
at sun.rmi.transport.proxy.RMIMasterSocketFactory.createSocket(RMIMasterSocketFactory.java:146)
at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:613)
... 23 more
I get this exception when I try to connect a remote client to my server. In both, server and client the hostName for the registryUrl of rmi is the public IP address of the server. I also tried to put localhost in server but the error doesn't change.
My java.policy is set to grant all connections to all ports and I have no firewalls enabled in the server or the client.
Any suggestions what could be?
This is item A.1 in the RMI FAQ. You need to either fix your /etc/hosts file or set the java.rmi.server.hostname property at the server.
PROBLEM SOLVED
I had exactly the same error. When the remote object got binded to the rmiregistry it was attached with the loopback IP Address which will obviously fail if you try to invoke a method from a remote address. In order to fix this we need to set the java.rmi.server.hostname property to the IP address where other devices can reach your rmiregistry over the network. It doesn't work when you try to set the parameter through the JVM. It worked for me just by adding the following line to my code just before binding the object to the rmiregistry:
System.setProperty("java.rmi.server.hostname","192.168.1.2");
In this case the IP address on the local network of the PC binding the remote object on the RMI Registry is 192.168.1.2.
you can use LocateRegistry such as:
Registry rgsty = LocateRegistry.createRegistry(1888);
rgsty.rebind("hello", hello);
I found many of the Q&A on this topic, not nothing was helping me - that's because my issue was more basic ( what can I say I am not a networking guru :) ). My ip address in /etc/hosts was incorrect. What I had tried included the following for CATALINA_OPTS:
CATALINA_OPTS="$CATALINA_OPTS -Djava.awt.headless=true -Xmx128M -server
-Dcom.sun.management.jmxremote
-Dcom.sun.management.jmxremote.port=7091
-Dcom.sun.management.jmxremote.authenticate=false
-Dcom.sun.management.jmxremote.ssl=false
-Djava.rmi.server.hostname=A.B.C.D" #howeverI put the wrong ip here!
export CATALINA_OPTS
My problem was that I had changed my ip address many months ago, but never updated my /etc/hosts file. it seems that by default the jconsole uses the hostname -i ip address in some fashion even though I was viewing local processes. The best solution was to simply change the /etc/hosts file.
The other solution which can work is to get your correct ip address from /sbin/ifconfig and use that ip address when specifying the ip address in, for example, a catalina.sh script:
-Djava.rmi.server.hostname=A.B.C.D
If you're running in a Linux environment, open the file /etc/hosts.allow
add the following line
ALL
Wildcards
Also check the /etc/hostname and /etc/host to see if there might be something wrong there.
I had to change my / etc / host from
127.0.0.1 localhost
127.0.1.1 AMK
to
127.0.0.1 localhost
127.0.0.1 AMK
also wrote in ALL in the file /etc/hosts.allow which was previously completely empty
Now everything works
do not know how safe it is. you have to read more about possible options for /etc/hosts.allow to do something that requires a touch of security.
Maybe your rmiregistry not be created before client trying connect to your server and it would lead to this exception.In Linux, you can use "netstat" to check your rmiregistry be bond on the right port you assigned in java code.
If you've tried modifying etc/hosts and adding java.rmi.server.hostname property as well but still registry is being bind to 127.0.0.1
the issue for me was resolved after explicitly setting System property through code though the same property wasn't picked from jvm args
It works for me after getting rid of "::1" in /etc/hosts.
I had the same exact problem and my issue was that I had 2 IP addresses from 2 different networks configured in the etc/hosts as below.
10.xxx.x.xxx localhost
192.xxx.x.xxx localhost
This should be because there was a conflict as to which IP to be used for the other devices to reach the rmiregistry over the network.
Once I removed the extra-record that is not required, I was able to solve the issue.
So my etc/hosts file had only the following record.
10.xxx.x.xxx localhost
In my case I was unable to edit the hosts file because using a pc from the university.
I fixed the problem running rmiregistry in another port (instead of 1099) with:
rmiregistry <port>
and then running the server on that port.
It was basically an error caused by occupied port.
when you want to connect to remote server with RMI you must add a system property same as:
System.setProperty("java.rmi.server.hostname","Ip or DNS of the server");
or add environment variable.
For me I got Connection Refused and solve it by adding this line of code in server side:
java -jar -Djava.rmi.server.hostname="ip or dns of the server" packageName.jar
Thank to other guy for guide me to solve it.
On Windows make sure your Windows firewall is correctly configure / disabled. I had to disable the Windows firewall (because I didn't bother with configuring it) to get things to work even when I was testing with localhost.
When I got the same error on my machine ("connection is refused"), the reason was that I had defined the following on the server side:
Naming.rebind("rmi://localhost:8080/AddService"
,addService);
Thus the server binds both the IP = 127.0.0.1 and the port 8080.
But on the client side I had used:
AddServerInterface st = (AddServerInterface)Naming.lookup("rmi://localhost"
+"/AddService");
Thus I forgot to add the port number after the localhost, so I rewrote the above command and added the port number 8080 as follows:
AddServerInterface st = (AddServerInterface)Naming.lookup("rmi://localhost:8080"
+"/AddService");
and everything worked fine.
You can simply use:
on server side:
Registry <objectName1> = LocateRegistry.createRegistry(1099);
Registry <objectName2> = LocateRegistry.getRegistry();
on Client Side:
Registry <object name you want> = LocateRegistry.getRegistry();
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
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 ).
i have one server installed in my system.It takes one of the ip addresses and acts as own system.
In my java program i connect to that server using the following code.
ServiceInstance si = new ServiceInstance(new URL("https://10.100.13.36/sdk"), "user", "password", true);
true indicates the ignore certificate to be true.
when i tried to execute with false parameter it says the following error.
CertificateException: No subject alternative names matching IP address 10.100.13.36 found
i got here that i have to use the dns name instead of ip address in case of certificate mode of server.
So i found in the server configuration settings that the server is taking the DNS name as localhost.localdomain
so i tried with the url as https://localhost.localdomain/sdk
it has shown the error that localhost.locadomain has not been found.
i guess it has some problem with DNS name resolution with localhost as my system and localhost.localdomain as my server dns name.
can we find the dns name with giving ip address through java program.So that it finds the DNS name on its own and pass the value in the url.
can anybody give some suggestion on this.
Thank you..
A DNS name is assigned by your local DNS server. The name localhost.localdomain is usually assigned in the host file so various local operations function (e.g., system logging, sending email to the root user from periodic tasks). I would guess that your server is not registered in the local DNS server. It is rare that locally run virtual machines actually have a valid registration in DNS - this is especially true for Linux systems running in a Windows environment.
If it were registered in DNS and both your server and client were using the same DNS hierarchy, then all that you need to do is create an java.net.InetAddress using the IP address of the machine and call getCanonicalHostName() to retrieve its DNS name. If it does not have a name registered in the local DNS server, then you will simply get the IP address back.
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.