Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Obtaining domain name using Java

Tags:

java

How do I obtain the domain name of the machine I am running on using Java?
For eg, my machine is a server whose domain name could be ec2-44-555-66-777.compute-1.amazonaws.com

I tried InetAddress.getLocalHost().getHostName() but that doesn't give me the name above. That gives me the hostname which looks similar to ip-0A11B222

like image 306
stumped Avatar asked May 04 '11 23:05

stumped


2 Answers

I guess you can try InetAddress.getCanonicalHostName() or InetAddress.getName() methods. Assuming there is a proper name service running on your net these two should do the trick.

The JavaDocs for getCanonicalHostName() says

Gets the fully qualified domain name for this IP address. Best effort method, meaning we may not be able to return the FQDN depending on the underlying system configuration.

So if you want to get your local FQDN, you can typically call: InetAddress.getLocalHost().getCanonicalHostName()

like image 92
Edwin Dalorzo Avatar answered Sep 28 '22 23:09

Edwin Dalorzo


getCanonicalHostName gives you the fully qualified domain name. I have tried using InetAddress.getLocalHost().getHostname() but it just gets the hostname value you see in command line which may or may not contain the fully qualified name.

To check if the fully qualified domain name is set using command line (in linux), use hostname --fqdn.

getCanonicalHostName

public String getCanonicalHostName() Gets the fully qualified domain name for this IP address. Best effort method, meaning we may not be able to return the FQDN depending on the underlying system configuration.

/** Main.java */
import java.net.InetAddress;  

public class Main {

  public static void main(String[] argv) throws Exception {

    byte[] ipAddress = new byte[] {(byte)127, (byte)0, (byte)0, (byte)1 };
    InetAddress address = InetAddress.getByAddress(ipAddress);
    String hostnameCanonical = address.getCanonicalHostName();
    System.out.println(hostnameCanonical);
  }
}

Example is taken from: http://www.java2s.com/Tutorials/Java/java.net/InetAddress/Java_InetAddress_getCanonicalHostName_.htm

like image 30
biniam Avatar answered Sep 28 '22 23:09

biniam