I have this simple server code:
public class Server {
public static void main(String[] args) {
try {
ServerSocket sSocket = null;
int serverPort = 57293;
try {
sSocket = new ServerSocket(serverPort);
Socket userSocket = sSocket.accept();
System.out.println(userSocket.getInetAddress().toString());
} catch (IOException listenEX) {
System.out.println("Could not listen on port: " + serverPort);
}
sSocket.close();
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
}
the server listens on port 57293 and on IP 0.0.0.0
it just waits for one connection and then prints the IP address of the client. Here is the client code:
public class Client {
public static void main(String[] args) throws IOException {
Socket serverSocket = new Socket("192.168.217.1", 57293);
DataInputStream in = new DataInputStream(serverSocket.getInputStream());
DataOutputStream out = new DataOutputStream(serverSocket.getOutputStream());
}
}
now as a server IP inside the client I enter the local ip of my computer. If I do so the server will print the same IP as a result which is /192.168.217.1
otherwise if in the client’s code I change the line
Socket serverSocket = new Socket("192.168.217.1", 57293);
to
Socket serverSocket = new Socket("127.0.0.1", 57293);
I just changed the servers IP the server will print the 127.0.0.1 IP to be the client’s IP address.
I don’t understand what’s going on here. It seems like the server is not printing the client’s IP address but the address of itself.
How can I avoid this from happening? I would want the server to print 192.168.217.1 if the client runs locally as well
127.0.0.1 is the loopback address. It is only visible from inside that host. The only way the client can connect to it is to use it itself. So the source and target addresses will be the same.
I don’t understand why this is a problem for you. 127.0.0.1 always means the local host, regardless of what the host’s external IP might be. There is nothing wrong with the result you are getting. It is a perfectly valid IP address and it correctly identifies the client.