Question

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.

Was it helpful?

Solution

Try

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

OTHER TIPS

Instead of calling InetAddress.getLocalHost() you want to create the address from x:

InetAddress a = InetAddress.getByName(x);

The rest of your code would stay the same..

oh, and you probably want to return a.getHostName() not x

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top