Java - Getting a server's hostname and/or ip address from client

Javier Pena picture Javier Pena · Nov 16, 2013 · Viewed 13.2k times · Source

So here is my situation. I need to use sockets in creating connections between server and client. This cannot be negotiated. I have a server running and listening using something like this

ServerSocket serverSocket = new ServerSocket(portNumber);
        while (listening) {
            new MultiClientThread(serverSocket.accept()).start();
        }

and I need a client to connect to the "portNumber" being listened to. The problem is I am using this line of code for the client.

Socket socket = new Socket(hostName, portNumber);

And I do not know how to get the "hostName" part for the parameters. Is it possible to get the "hostName" if I knew the portNumber that was being listened to? Or maybe another way to word it is how can I connect to a server listening to a port using tcp connections.

Answer

Femaref picture Femaref · Nov 16, 2013

hostName usually is hardcoded in the client. It can either be an ip address or a domain name. If the server is running the same machine, you can use localhost or 127.0.0.1 as hostname.