Obtain FQDN in Java
Asked Answered
C

3

7

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?

Chaliapin answered 1/9, 2011 at 11:12 Comment(1)
I was wondering, if you set an entry in the etc/hosts of Windows does your code work?Disservice
P
2

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.

Peyter answered 1/9, 2011 at 14:55 Comment(0)
S
1

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.

Stuffing answered 23/8, 2017 at 12:40 Comment(0)
G
0

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));
}
Galactic answered 1/8, 2020 at 16:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.