简体   繁体   中英

How can I get domain name in Java

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.

您可以从您的环境中获取域名。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM