Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get hostname from CNAME in Java?

Tags:

java

cname

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".

like image 438
Jesse Avatar asked Dec 29 '25 05:12

Jesse


1 Answers

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.

like image 142
Fabian Frank Avatar answered Dec 31 '25 19:12

Fabian Frank