0

How do I convert the IP to domain name (not hostname) in java?

C:\WINDOWS\system32>ping google.com Pinging google.com [142.251.42.78] with 32 bytes of data:

public static void main(String[] args) {
    
    try {
         System.out.println("Response : "+ new RestTemplate().execute("http://142.251.42.78:8080", HttpMethod.GET, null, null, "").toString());
    } catch (Exception e ) {System.out.println("Error : "+e.getMessage());}

    System.out.println("\n--------------\n");

    try {
         System.out.println("Response : "+ new RestTemplate().execute("https://142.251.42.78:443", HttpMethod.GET, null, null, "").toString());
    } catch (Exception e ) {System.out.println("Error : "+e.getMessage());}
    
    System.out.println("\n--------------\n");
    
    try {
         byte[] ipAddr = new byte[] {(byte) 142, (byte)251, (byte) 42, (byte) 78 };
         InetAddress addr = InetAddress.getByAddress(ipAddr);
         System.out.println(addr.getCanonicalHostName());
         System.out.println(addr.getHostAddress());
         System.out.println(addr.getHostName());
         System.out.println(addr.getLocalHost());
         System.out.println(addr.getLoopbackAddress());
            
    } catch (Exception e ) {System.out.println("Error : "+e.getMessage());}
}

Output:

17:00:33.324 [main] DEBUG org.springframework.web.client.RestTemplate - Created GET request for "http://142.251.42.78:8080"

Error : I/O error on GET request for "http://142.251.42.78:8080": Connection timed out: connect; nested exception is java.net.ConnectException: Connection timed out: connect


17:00:54.773 [main] DEBUG org.springframework.web.client.RestTemplate - Created GET request for "https://142.251.42.78:443" Error : I/O error on GET request for "https://142.251.42.78:443": java.security.cert.CertificateException: No subject alternative names matching IP address 142.251.42.78 found; nested exception is javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: No subject alternative names matching IP address 142.251.42.78 found


bom12s21-in-f14.1e100.net 142.251.42.78 bom12s21-in-f14.1e100.net *L000/192.168.0.149 localhost/127.0.0.1

Satya Prakash
  • 676
  • 7
  • 15
  • 3
    How do you expect this to work considering that multiple domain names can point to the same IP address? – OH GOD SPIDERS Jun 21 '22 at 11:38
  • @OHGODSPIDERS - i know in that case we need multiple domains ! – Satya Prakash Jun 21 '22 at 12:51
  • InetAddress[] machines = InetAddress.getAllByName("google.com"); for(InetAddress address : machines) { if(address!=null) { if (address instanceof Inet4Address) { if(!StringUtils.isEmpty(address.getHostAddress())) System.out.println(address.getHostAddress()); } } } – Satya Prakash Jun 21 '22 at 12:52

0 Answers0