Java TCP socket: java.net.ConnectException: connect: Address is invalid on local machine, or port is not valid on remote machine
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.)
Android_enthusiast
Updated on June 05, 2022Comments
-
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 useInetAddress.getLocalHost()
I getjava.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 usesocket.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