How can you get the hostname of a server given a CNAME (canonical name) in Java?
The example would be that I have the CNAME "xyz" but I want to get the associated hostname "myhost".
I tried using java.net.InetAddress.getHostName() but it just returned the CNAME that I was giving.
For example:
String myCNAME = "xyz";
InetAddress inetAddress = InetAddress.getByName(myCNAME);
System.out.printf("My hostname = '%s'", inetAddress.getHostName());
Just returns the given CNAME:
My hostname = 'xyz'
Instead I want to get the hostname "myhost".
Java comes with an included DNS client, but it's unfortunately not very well documented and not very visible when you search the web for things like "Java DNS". The following snippet uses Java's built-in DNS client to resolve a CNAME record:
Properties env = new Properties();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory");
InitialDirContext idc = new InitialDirContext(env);
Attributes attrs = idc.getAttributes("something.example.com", new String[]{"CNAME"});
Attribute attr = attrs.get("CNAME");
System.out.println(attr.get());
Some (not so great) documentation exists: https://docs.oracle.com/javase/jndi/tutorial/beyond/env/overview.html https://docs.oracle.com/javase/8/docs/technotes/guides/jndi/jndi-dns.html (can't find a newer link for 10+)
The disadvantage of solutions that rely on InetAddress is that they don't consider the CNAME record, but instead perform an A lookup followed by a reverse lookup to get back from the IP to the hostname, but the hostname returned by the reverse lookup is often a different hostname than the hostname that the CNAME lookup actually points at.
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