简体   繁体   中英

Obtain FQDN in Java

I am trying to obtain the FQDN of a windows machine in my domain, using Java code.

I have tried the InetAddress.getByName("machine-1").getCanonicalHostName() but only returns the machine name.

On the other hand if I ping "machine-1" I get the fully domain name.

Do you know how to do it?

The simple answer is that what you suggest works if it can.

The API does state that it will return the FQDN if it can. This depends on the system configuration.

The code you post does work for me on a windows domain machine, but I can't say why it wouldn't for you.

If you are unable to alter the machine / domain configuration such that java can pick it up, and it is essential for your code to use that FQDN, you could resort to executing the ping command from java and parse the results at least as a temporary measure.

Super late reply, perhaps it will help the next traveler.

InetAddress.getLocalHost().getCanonicalHostName() 

This will return the FQDN - My JVM version is 1.8.0_144

I found this JDK bug report http://bugs.java.com/view_bug.do?bug_id=7166687 which might explain why there is so much confusion.

InetAddress.getLocalHost().getHostName()

This returns just the host name now.

Another late reply, but I needed this today also and the answer to call getCanonicalHostName was far too slow for me, it seems to require a DNS lookup.

If you don't mind using JNA (I already required it in my project) this will do it for you very fast (for Windows only):

int format = WinBase.COMPUTER_NAME_FORMAT.ComputerNameDnsFullyQualified;
char buffer[] = new char[256];
IntByReference lpnSize = new IntByReference(0);
lpnSize.setValue(buffer.length);
boolean success = Kernel32.INSTANCE.GetComputerNameEx(format, buffer, lpnSize);

if (success) {
    System.out.println(Native.toString(buffer));
}

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