async dns support

This commit is contained in:
Eric A. Miller
2013-10-15 22:55:44 -04:00
parent 325e59bade
commit 8946cf291b
10 changed files with 97 additions and 148 deletions

View File

@@ -4,11 +4,12 @@ use strict;
use warnings FATAL => 'all';
use Net::DNS;
use AnyEvent::DNS;
use base 'Exporter';
our @EXPORT = ();
our @EXPORT_OK = qw/
hostname_from_ip ipv4_from_hostname
hostname_from_ip hostnames_resolve_async ipv4_from_hostname
/;
our %EXPORT_TAGS = (all => \@EXPORT_OK);
@@ -75,5 +76,46 @@ sub ipv4_from_hostname {
return undef;
}
=head2 hostnames_resolve_async( $ips )
This method uses a fully asynchronous and high-performance pure-perl stub
resolver C<AnyEvent::DNS>.
Given a reference to an array of hashes will resolve the C<IPv4> or C<IPv6>
address in the C<ip> or C<alias> key of each hash into its hostname which
will be inserted in the C<dns> key of the hash. The resolver does also
forward-lookups to verify that the resolved hostnames point to the
address.
Returns the supplied reference to an array of hashes with dns values for
addresses which resolved.
=cut
sub hostnames_resolve_async {
my $ips = shift;
my $resolver = AnyEvent::DNS->new();
# Set up the condvar
my $done = AE::cv;
$done->begin( sub { shift->send } );
foreach my $hash_ref (@$ips) {
my $ip = $hash_ref->{'ip'} || $hash_ref->{'alias'};
$done->begin;
AnyEvent::DNS::reverse_verify $ip,
sub { $hash_ref->{'dns'} = shift; $done->end; };
}
# Decrement the cv counter to cancel out the send declaration
$done->end;
# Wait for the resolver to perform all resolutions
$done->recv;
return $ips;
}
1;