Reputation: 86627
I want to resolve the domain name from a clients IP address. For a test, I used stackoverflow as follows. But when I use the ip to resolve the domain, I still get only the IP as result.
String ip = InetAddress.getByName("www.stackoverflow.com").getHostAddress();
System.out.println(ip);
System.out.println(InetAddress.getByName(ip).getHostName());
System.out.println(InetAddress.getByName(ip).getCanonicalHostName());
System.out.println(InetAddress.getByName(ip).getHostAddress());
Result:
151.101.129.69
151.101.129.69
151.101.129.69
151.101.129.69
How can I get the domain name (stackoverflow / www.stackoverflow.com) if I'd only have the ip 151.101.129.69
given?
Upvotes: 1
Views: 1202
Reputation: 718658
I tried a forward and then reverse lookup on "www.stackoverflow.com" and it is clear that the admins for stackoverflow have not set up the DNS PTR record(s) for this IP that would allow Java to reverse lookup the site's DNS name(s).
(Another scenario where reverse lookup will fail is when no DNS name maps to a given IP address.)
This is not a Java specific problem. You will get the same behavior in any language. It is actually a consequence of DNS's design, and the way that DNS is used in practice.
There is no real solution to this. You need to write your application code to allow for IP addresses that you cannot resolve to a DNS address.
For the record, this is what I got using the dig
tool. (Some details obscured for security reasons).
$ dig www.stackoverflow.com
; <<>> DiG 9.11.3-1ubuntu1.13-Ubuntu <<>> www.stackoverflow.com
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 52578
;; flags: qr rd ra; QUERY: 1, ANSWER: 5, AUTHORITY: 0, ADDITIONAL: 1
;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 4096
; COOKIE: zzzzzz (good)
;; QUESTION SECTION:
;www.stackoverflow.com. IN A
;; ANSWER SECTION:
www.stackoverflow.com. 3600 IN CNAME stackoverflow.com.
stackoverflow.com. 2760 IN A 151.101.129.69
stackoverflow.com. 2760 IN A 151.101.193.69
stackoverflow.com. 2760 IN A 151.101.1.69
stackoverflow.com. 2760 IN A 151.101.65.69
;; Query time: 22 msec
;; SERVER: xx.xx.xx.xx
;; WHEN: Wed Oct 07 19:49:12 AEDT 2020
;; MSG SIZE rcvd: 156
$ dig -x 151.101.129.69
; <<>> DiG 9.11.3-1ubuntu1.13-Ubuntu <<>> -x 151.101.129.69
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NXDOMAIN, id: 43513
;; flags: qr rd ra; QUERY: 1, ANSWER: 0, AUTHORITY: 1, ADDITIONAL: 1
;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 4096
; COOKIE: zzzzzz (good)
;; QUESTION SECTION:
;69.129.101.151.in-addr.arpa. IN PTR
;; AUTHORITY SECTION:
151.in-addr.arpa. 3600 IN SOA pri.authdns.ripe.net. dns.ripe.net. 1586416382 3600 600 864000 3600
;; Query time: 34 msec
;; SERVER: xx.xx.xx.xx
;; WHEN: Wed Oct 07 19:49:26 AEDT 2020
;; MSG SIZE rcvd: 168
Upvotes: 2