Search code examples
javadnshostnameinetaddress

Java - How to invoke a IP Address to find host name?


The code I've made automatically returns the host name.

But instead of returning my machine's host name every time. I want to checkup on other machines as well (for testing purpose).

By that I mean, every time I call the method, it'll ask me to enter an IP address, and then return me the host name of the address I've entered.

For example:

  1. run method findH(String f)
  2. I type 127.0.0.1 (IP address/hostname) for String f
  3. it returns me my host name: MyPC etc (made up).

Here's my code:

import java.net.InetAddress;

public class Search
{


    public String findH(String x) throws Exception {
        InetAddress a = InetAddress.getLocalHost();
        String s = a.getHostName();
        System.out.println("Host Name is: " + a.HostName());

        return x;
    }
}

Thanks in advance. I know my description isn't the best, but let me know if there's any ambiguity.


Solution

  • Try

    public String findH(String x) throws Exception {
        InetAddress addr = InetAddress.getByName(x);
        return addr.getHostName();
    }