Reverse DNS lookup in perl
Asked Answered
C

8

13

How do I perform a reverse DNS lookup, that is how do I resolve an IP address to its DNS hostname in Perl?

Colene answered 17/9, 2008 at 17:14 Comment(0)
M
20

gethostbyaddr and similar calls. See http://perldoc.perl.org/functions/gethostbyaddr.html

Memphian answered 17/9, 2008 at 17:15 Comment(0)
D
22

If you need more detailed DNS info use the Net::DNS module, here is an example:

use Net::DNS;
my $res = Net::DNS::Resolver->new;

# create the reverse lookup DNS name (note that the octets in the IP address need to be reversed).
my $IP = "209.85.173.103";
my $target_IP = join('.', reverse split(/\./, $IP)).".in-addr.arpa";

my $query = $res->query("$target_IP", "PTR");

if ($query) {
  foreach my $rr ($query->answer) {
    next unless $rr->type eq "PTR";
    print $rr->rdatastr, "\n";
  }
} else {
  warn "query failed: ", $res->errorstring, "\n";
}

Original Source EliteHackers.info, more details there as well.

Dirty answered 17/9, 2008 at 17:32 Comment(0)
M
20

gethostbyaddr and similar calls. See http://perldoc.perl.org/functions/gethostbyaddr.html

Memphian answered 17/9, 2008 at 17:15 Comment(0)
C
17
use Socket;
$iaddr = inet_aton("127.0.0.1"); # or whatever address
$name  = gethostbyaddr($iaddr, AF_INET);
Colene answered 17/9, 2008 at 17:22 Comment(0)
R
4
perl -MSocket -E 'say scalar gethostbyaddr(inet_aton("69.89.27.250"), AF_INET)'

Returns: Can't find string terminator "'" anywhere before EOF at -e line 1.

perl -MSocket -E "say scalar gethostbyaddr(inet_aton(\"69.89.27.250\"), AF_INET)"

Returns: box250.bluehost.com

I have to change the line to use double quotes and then escape out the quotes around the IP address

Rentschler answered 9/10, 2012 at 23:51 Comment(1)
That's probably because you're using cmd.exe under windows.Paschall
R
2

one-liner:

perl -MSocket -E 'say scalar gethostbyaddr(inet_aton("79.81.152.79"), AF_INET)'
Rolan answered 3/9, 2009 at 13:29 Comment(0)
S
1

If gethostbyaddr doesn't fit your needs, Net::DNS is more flexible.

Spier answered 17/9, 2008 at 17:14 Comment(0)
G
1

There may be an easier way, but for IPv4, if you can perform ordinary DNS lookups, you can always construct the reverse query yourself. For the IPv4 address A.B.C.D, look up any PTR records at D.C.B.A.in-addr.arpa. For IPv6, you take the 128 hex nibbles and flip them around and append ipv6.arpa. and do the same thing.

Giulietta answered 17/9, 2008 at 17:17 Comment(0)
T
0

This might be useful...

$ip = "XXX.XXX.XXX.XXX" # IPV4 address.
my @numbers = split (/\./, $ip);
if (scalar(@numbers) != 4)
{
    print "$ip is not a valid IP address.\n";
    next;
}
my $ip_addr = pack("C4", @numbers);
# First element of the array returned by gethostbyaddr is host name.
my ($name) = (gethostbyaddr($ip_addr, 2))[0];
Tabethatabib answered 18/9, 2008 at 22:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.