Raphael D.
Raphael D.

Reputation: 778

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

  1. 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)
    
  2. 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?

Upvotes: 0

Views: 7652

Answers (1)

Stephen C
Stephen C

Reputation: 718886

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!

Upvotes: 2

Related Questions