Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot get hostname from getHostName

Tags:

java

I am trying to get hostname/computer name using this method. Unfortunately i only can get localhost but not other computer.

private String getHostName(String _strIP) {
    try {
        InetAddress inetAddress = InetAddress.getByName(_strIP);
        System.out.println("getHostAddress : " + inetAddress.getHostAddress());
        System.out.println("getHostName : " + inetAddress.getHostName());
        System.out.println("getCanonicalHostName : " + inetAddress.getCanonicalHostName());
        return inetAddress.getHostName();            
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }
    return strDefaultHostName;
}

the result (not localhost)

getHostAddress : 192.168.2.139
getHostName : 192.168.2.139
getCanonicalHostName : 192.168.2.139

the result (localhost)

getHostAddress : 127.0.0.1
getHostName : localhost
getCanonicalHostName : localhost

Thank you

like image 487
Joe Ijam Avatar asked Feb 05 '26 19:02

Joe Ijam


1 Answers

We've established roughly what the problem is in tangens' answer.

I think you can fix the problem pretty simply by putting host names into your hosts file.

%SystemRoot%\system32\drivers\etc\hosts

is the file you're looking for; localhost is defined here. You want to put a name and address line in it for every host you want to resolve.

I've never tried this. If it doesn't work, you get your money back.


Update

The above is the "quick hack" solution. This essentially entails that whenever someone manually changes the IP address of a host you're interested in, someone must at the same time change the hosts files on any machines that want to access those hosts.

The other alternative is to operate your own DNS server. You still need to update IP addresses when a host's address changes, but you only need to do so in one place, and you get both forward and reverse name resolution throughout your network. This takes more setting up but is easier to maintain in the long run.

Here is a very useful reference: http://www.dns.net/dnsrd/servers/windows.html

They mention that the "built in" Microsoft DNS server is a terrible solution (up until the one in Windows 2003 Server) but mention at least two alternatives, one commercial and one free. BIND is what is currently holding much of the Internet together, DNS-wise, and it's great that they have a Windows port too.

like image 74
Carl Smotricz Avatar answered Feb 07 '26 07:02

Carl Smotricz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!