Skip to content

Instantly share code, notes, and snippets.

@fskale
Created July 11, 2019 10:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fskale/d3a42fc97cf861da9576b677d548600c to your computer and use it in GitHub Desktop.
Save fskale/d3a42fc97cf861da9576b677d548600c to your computer and use it in GitHub Desktop.
Non-Blocking DNS Resolution using Net::DNS::Native and Mojo::IOLoop::Delay
#!/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;
@fskale
Copy link
Author

fskale commented Jul 11, 2019

Output:

Host google.de:
	IP: 2a00:1450:4001:819::2003 Family: IPV6
	IP: 172.217.16.131 Family: IPV4

Host google.com:
	IP: 2a00:1450:4001:809::200e Family: IPV6
	IP: 216.58.208.46 Family: IPV4

Host google.at:
	IP: 2a00:1450:4001:806::2003 Family: IPV6
	IP: 172.217.22.3 Family: IPV4

Host github.com:
	IP: 140.82.118.3 Family: IPV4

Host google.it:
	IP: 2a00:1450:4001:817::2003 Family: IPV6
	IP: 172.217.21.227 Family: IPV4

FINISHED

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment