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
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()
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With