Java TCP socket: java.net.ConnectException: connect: Address is invalid on local machine, or port is not valid on remote machine

11,740

You're using the four-argument form of the Socket constructor (really unusual; it's normal to only use the two argument form and let the OS figure out the local address side for itself) so you need to make sure that the two addresses associated with the socket are compatible, i.e., that it is possible to route packets that way. In particular, if either end is localhost, the other end must be too because that address is only ever routed over the loopback network interface.

The simplest fix for you (on the client side) is going to be to switch to using the two-argument constructor, leaving the OS to figure out the rest of it for you; it does a good job. (If the server depends on the client connection coming from a specific port number, that's awful and terribly terribly fragile.)

Share:
11,740
Android_enthusiast
Author by

Android_enthusiast

Updated on June 05, 2022

Comments

  • Android_enthusiast
    Android_enthusiast almost 2 years

    I am creating socket using socket = new Socket(host, port, InetAddress.getLocalHost(), clientPort);. I want the socket to listen to particular port at client side. But when I use InetAddress.getLocalHost() I get java.net.ConnectException: connect: Address is invalid on local machine, or port is not valid on remote machine.

    But when I use InetAddress.getByName("localhost") it works fine. But I require IP address of the machine in server side. So when I use socket.getInetAddress() I want ipadress and not 127.0.0.1.

    Can anyone please help. I am using eclipse. Can this be a firewall issue?

    Thanks