Check Hostname Resolution Forward and Backward Using Python or Java
Luke Hebert
- 2 minutes read - 379 wordsInconsistent forward and reverse DNS lookups can cause a cascade of cluster and security issues. If your hostname, IP, and reverse record do not all resolve to the same value, you will see intermittent failures across services that depend on name resolution. The commands below give you a fast, side-by-side comparison of what the system resolver and the language-level resolver each return, so you can spot mismatches in seconds.
Python
The following one-liners print the system resolver output alongside the Python resolver output for easy comparison.
python -c "import socket; print socket.getfqdn(); print socket.gethostbyname(socket.getfqdn())"paste <(hostname; hostname -i; echo) <(python -c "import socket; print '\t' + socket.getfqdn(); print '\t\t\t' + socket.gethostbyname(socket.getfqdn())")For a more detailed report that includes the reverse DNS lookup:
printf '\nSystem Resolver Library\n---\nHostname: ' ; hostname; printf 'IP: '; hostname -i; echo '---'; printf '\n'; python -c "import socket; ip=str(socket.gethostbyname(socket.getfqdn())); rdns=socket.gethostbyaddr(ip); print 'Python Resolver Library\n---\nFully Qualified Domain Name: ' + socket.getfqdn(); print 'Resolves To: ' + socket.gethostbyname(socket.getfqdn()) + '\n---\n'; print '---\nRDNS For ' + ip; print 'Resolves To: ' + rdns[0] + '\n---\n'"Example output:
System Resolver Library
---
Hostname: serv
IP: 127.0.1.1 192.168.1.7
---
Python Resolver Library
---
Fully Qualified Domain Name: serv.local
Resolves To: 127.0.1.1
---
---
RDNS For 127.0.1.1
Resolves To: serv.local
---Java
If Python is not available on the target host, a small Java class can do the same job. The class below returns the local hostname, its IP, and the reverse lookup for both.
📎 Download javadnslookup.class
📎 Download javadnslookup.java
Standalone Java DNS Lookup
If Java is your only tool and you also want to test DNS lookups against a specific hostname, use the class below. It accepts (and requires) a hostname argument.
java -classpath . JavaDnsLookup 2024-1.example.comYour Current IP address : 10.16.88.51
Your Current Hostname : ip-10-16-88-51.ec2.internalJavaDNS (No Argument)
For a quick local check without specifying a hostname:
/usr/java/jdk1.7.0_67-example/jre/bin/java -classpath . JavaDNSYour current IP address : 172.19.50.102
Your current Hostname : kms-1.lab.atx.example.com
Your Reverse IP address : 172.19.50.102
Your Reverse Hostname: kms-1.lab.atx.example.comIf the forward and reverse lookups do not return the same hostname, check your /etc/hosts file, the DNS zone records, and any split-horizon DNS configuration before troubleshooting application-level issues.