How can I get domain name in Java

Sachin picture Sachin · Jan 28, 2014 · Viewed 11.5k times · Source

I need domain name. Currently I am getting domain name as follows

InetAddress addr;
String hostnameCanonical;
try{
    addr = InetAddress.getByName(InetAddress.getLocalHost().getHostName());
    hostnameCanonical = addr.getCanonicalHostName();
    String   strDomainName=hostnameCanonical.substring(hostnameCanonical.indexOf(".")+1,      hostnameCanonical.lastIndexOf("."));
    System.out.println("strDomainName = "+strDomainName);
} 
catch (UnknownHostException e) {
e.printStackTrace();
}

Is there any better and efficient way of getting domain name? Thanks in advance.

Answer

guest picture guest · May 24, 2016

You can get domain name from your environment.

String domainname = System.getenv("USERDOMAIN");