Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 435
Javier Pena Avatar asked Nov 16 '13 16:11

Javier Pena


People also ask

How do you display the IP address and hostname of a local machine in Java?

The IP address and hostname of any local computer can be determined using the java. net. InetAddress class.

How do I find the IP address of a client connected to a server?

After the client establishes a successful connection to the server, the IP address of the client will be printed on the server console.

How do I find hostname from IP address?

Click the Windows Start button, then "All Programs" and "Accessories." Right-click on "Command Prompt" and choose "Run as Administrator." Type "nslookup %ipaddress%" in the black box that appears on the screen, substituting %ipaddress% with the IP address for which you want to find the hostname.

Which of the following command gives information about hostname or IP address?

The most popular and frequently used command to get the IP address of the host is the ping command.


1 Answers

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.

like image 70
Femaref Avatar answered Sep 23 '22 20:09

Femaref