25

My hosts file (C:\WINDOWS\system32\drivers\etc\hosts) has a bunch of IP Address to host name mappings:

# Switches
192.168.200.254       sw-con-ctrl
192.168.201.253    sw-con-ctrl-2
192.168.201.254       sw-con-ctrl-1
# 192.168.188.1       sw-con-ctrl-ylw-1
# 192.168.189.1       sw-con-ctrl-blu
192.168.190.62        access-console

# Routers
192.168.21.1          rtr1
192.168.22.1          rtr2

I am trying to find a way to convert from an IPAddress to the HostName programmatically through Java APIs.

Pseudocode:

IPAddress ip = new IPAddress("192.168.190.62");
String host = ip.getHost();
System.out.println(host);  //prints "access-console"
mainstringargs
  • 13,563
  • 35
  • 109
  • 174

4 Answers4

51

I tried the code from here and it works. Namely:

  InetAddress addr = InetAddress.getByName("192.168.190.62");
  String host = addr.getHostName();
  System.out.println(host);
Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
user85509
  • 36,612
  • 7
  • 33
  • 26
2

This works as the javadocs say only local when no reverse lookup is needed: If a literal IP address is supplied, only the validity of the address format is checked.

If someone know a way without using third party jars to do the remote lookup...

RudeUrm
  • 46
  • 2
2

There are methods in the InetAddress class for that. I think you'll want either getHostName or getCanonicalHostName, depending on your need.

Umpa
  • 334
  • 11
  • 16
Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
0
import java.net.InetAddress;
import java.net.UnknownHostException;

public class Main02{
    public static void main(String[]args) throws UnknownHostException{
        InetAddress ia = InetAddress.getByName("46.228.47.114");
        System.out.println(ia.getHostName());
    }
}

Output :

ir2.fp.vip.ir2.yahoo.com

סטנלי גרונן
  • 2,917
  • 23
  • 46
  • 68