简体   繁体   中英

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

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

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, ie, 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.)

Sounds like confusion over client-side and server-side responsibilities - sounds like you're trying to get two Java applications talking to each other on the same host via TCP/IP, using Java Sockets.

If this is the case you first need to use a ServerSocket in the 'server' application to create a listening socket on all interfaces:

serverSocket = new ServerSocket(4444);

You should then be able to connect to the ServerSocket from the 'client' application by using a Socket to connect to the localhost:

clientSocket = new Socket("localhost", 4444);

The following page(s) looks like they cover this in detail:

All About Sockets

Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM