Created
July 11, 2019 10:41
-
-
Save fskale/d3a42fc97cf861da9576b677d548600c to your computer and use it in GitHub Desktop.
Non-Blocking DNS Resolution using Net::DNS::Native and Mojo::IOLoop::Delay
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env perl | |
use Mojo::Base -strict; | |
use Mojo::IOLoop::Delay; | |
use Net::DNS::Native; | |
use Socket qw(:addrinfo IPPROTO_UDP SOCK_DGRAM); | |
my $dns = Net::DNS::Native->new(pool => 5, extra_thread => 1); | |
my $d = Mojo::IOLoop::Delay->new; | |
$d->steps( | |
sub { | |
my $delay = shift; | |
for my $host ('google.com', 'google.at', 'google.de', 'google.it', | |
'github.com') | |
{ | |
my $end = $delay->begin; | |
my $fh = $dns->getaddrinfo($host, 161, | |
{protocol => IPPROTO_UDP, socktype => SOCK_DGRAM}); | |
Mojo::IOLoop->singleton->reactor->io( | |
$fh => sub { | |
my $reactor = shift; | |
$reactor->remove($fh); | |
my ($err, @res) = $dns->get_result($fh); | |
if ($err) { | |
printf("Error: Host: %s %s\n", $host, $err); | |
} | |
else { | |
printf("Host %s:\n", $host); | |
foreach my $entry (@res) { | |
my ($err, $ip, $servicename) | |
= getnameinfo($entry->{addr}, NI_NUMERICHOST); | |
if ($ip) { | |
printf("\tIP: %s Family: %s\n", | |
$ip, $ip =~ qr/(?::)/ ? q{IPV6} : q{IPV4}); | |
} | |
elsif ($err) { | |
printf("\tError: %s\n", $err); | |
} | |
} | |
} | |
printf("\n"); | |
$end->(); | |
} | |
)->watch($fh, 1, 0); | |
} | |
}, | |
sub { | |
my $delay = shift; | |
printf("FINISHED\n"); | |
} | |
)->wait; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output: