<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">package Net::DNS::Nameserver;

#
# $Id: Nameserver.pm 970 2011-12-13 10:51:06Z willem $
#
use vars qw($VERSION);
$VERSION = (qw$LastChangedRevision: 970 $)[1];


=head1 NAME

Net::DNS::Nameserver - DNS server class

=head1 SYNOPSIS

    use Net::DNS::Nameserver;

    $nameserver = new Net::DNS::Nameserver(
	LocalAddr	 =&gt; ['::1' , '127.0.0.1' ],
	LocalPort	 =&gt; "5353",
	ReplyHandler =&gt; \&amp;reply_handler,
	Verbose		 =&gt; 1,
	Truncate	 =&gt; 0
    );


=head1 DESCRIPTION

Instances of the C&lt;Net::DNS::Nameserver&gt; class represent DNS server
objects.  See L&lt;/EXAMPLE&gt; for an example.

=cut


use strict;
use integer;
use Carp qw(cluck);
use Net::DNS;

use IO::Socket;
use IO::Socket::INET;
use IO::Select;

use constant FORCE_INET4 =&gt; 0;

use constant DEFAULT_ADDR =&gt; 0;
use constant DEFAULT_PORT =&gt; 53;

use constant STATE_ACCEPTED   =&gt; 1;
use constant STATE_GOT_LENGTH =&gt; 2;
use constant STATE_SENDING    =&gt; 3;

use vars qw($has_inet6);

BEGIN {
	if (FORCE_INET4) {
		$has_inet6 = 0;
	} elsif (
		eval {
			require IO::Socket::INET6;
			IO::Socket::INET6-&gt;VERSION("2.01");
		}
		) {
		$has_inet6 = 1;
	} else {
		$has_inet6 = 0;
	}
}


#------------------------------------------------------------------------------
# Constructor.
#------------------------------------------------------------------------------

sub new {
	my ( $class, %self ) = @_;
	my $self = bless \%self, $class;
	if ( !exists $self{ReplyHandler} ) {
		if ( my $handler = UNIVERSAL::can( $class, "ReplyHandler" ) ) {
			$self{ReplyHandler} = sub { $handler-&gt;( $self, @_ ); };
		}
	}
	unless ( ref $self{ReplyHandler} eq "CODE" ) {
		cluck "No reply handler!";
		return undef;
	}

	# local server addresses must also be accepted by a resolver
	my @LocalAddr =
			ref $self{LocalAddr}
			? @{$self{LocalAddr}}
			: ( $self{LocalAddr} || DEFAULT_ADDR );
	my $resolver = new Net::DNS::Resolver;
	$resolver-&gt;force_v4(1) unless $has_inet6;
	$resolver-&gt;nameservers(undef);
	my @localaddresses = $resolver-&gt;nameservers(@LocalAddr);

	my $port = $self{LocalPort} || DEFAULT_PORT;
	$self{Truncate}	   = 1	 unless defined( $self{Truncate} );
	$self{IdleTimeout} = 120 unless defined( $self{IdleTimeout} );

	my @sock_tcp;						# All the TCP sockets we will listen to.
	my @sock_udp;						# All the UDP sockets we will listen to.

	# while we are here, print incomplete lines as they come along.
	local $| = 1 if $self{Verbose};

	foreach my $addr (@localaddresses) {

		#--------------------------------------------------------------------------
		# Create the TCP socket.
		#--------------------------------------------------------------------------

		print "\nCreating TCP socket $addr#$port - " if $self{Verbose};

		my $sock_tcp = inet_new(
			LocalAddr =&gt; $addr,
			LocalPort =&gt; $port,
			Listen	  =&gt; 64,
			Proto	  =&gt; "tcp",
			Reuse	  =&gt; 1,
			Blocking  =&gt; 0,
			);
		if ($sock_tcp) {
			push @sock_tcp, $sock_tcp;
			print "done.\n" if $self{Verbose};
		} else {
			cluck "Couldn't create TCP socket: $!";
		}

		#--------------------------------------------------------------------------
		# Create the UDP Socket.
		#--------------------------------------------------------------------------

		print "Creating UDP socket $addr#$port - " if $self{Verbose};

		my $sock_udp = inet_new(
			LocalAddr =&gt; $addr,
			LocalPort =&gt; $port,
			Proto	  =&gt; "udp",
			);

		if ($sock_udp) {
			push @sock_udp, $sock_udp;
			print "done.\n" if $self{Verbose};
		} else {
			cluck "Couldn't create UDP socket: $!";
		}

	}

	#--------------------------------------------------------------------------
	# Create the Select object.
	#--------------------------------------------------------------------------

	my $select = $self{select} = new IO::Select;

	$select-&gt;add(@sock_tcp);
	$select-&gt;add(@sock_udp);

	return undef unless $select-&gt;count;

	#--------------------------------------------------------------------------
	# Return the object.
	#--------------------------------------------------------------------------

	return $self;
}

#------------------------------------------------------------------------------
# inet_new - Calls the constructor in the correct module for making sockets.
#------------------------------------------------------------------------------

sub inet_new {
	if ($has_inet6) {
		return new IO::Socket::INET6(@_);
	} else {
		return new IO::Socket::INET(@_);
	}
}

#------------------------------------------------------------------------------
# make_reply - Make a reply packet.
#------------------------------------------------------------------------------

sub make_reply {
	my ( $self, $query, $peerhost, $conn ) = @_;

	my $reply = new Net::DNS::Packet();			# create empty reply packet
	$reply-&gt;header-&gt;qr(1);

	my $headermask;

	unless ($query) {
		print "ERROR: invalid packet\n" if $self-&gt;{Verbose};
		$reply-&gt;header-&gt;rcode("FORMERR");
		return $reply;
	}

	if ( $query-&gt;header-&gt;qr() ) {
		print "ERROR: invalid packet (qr was set, dropping)\n" if $self-&gt;{Verbose};
		return;
	}

	# question section returned to caller
	my @q = $query-&gt;question;

	$reply-&gt;push( "question", @q );

	my $opcode  = $query-&gt;header-&gt;opcode;
	my $qdcount = $query-&gt;header-&gt;qdcount;

	unless ($qdcount) {
		$reply-&gt;header-&gt;rcode("NOERROR");

	} elsif ( $qdcount &gt; 1 ) {
		print "ERROR: qdcount $qdcount unsupported\n" if $self-&gt;{Verbose};
		$reply-&gt;header-&gt;rcode("FORMERR");

	} else {
		my ($qr)   = @q;
		my $qname  = $qr-&gt;qname;
		my $qtype  = $qr-&gt;qtype;
		my $qclass = $qr-&gt;qclass;

		my $id = $query-&gt;header-&gt;id;
		print "query $id : $qname $qclass $qtype - " if $self-&gt;{Verbose};

		my ( $rcode, $ans, $auth, $add );

		if ( $opcode eq "QUERY" ) {
			( $rcode, $ans, $auth, $add, $headermask ) =
				&amp;{$self-&gt;{ReplyHandler}}( $qname, $qclass, $qtype, $peerhost, $query, $conn );

		} elsif ( $opcode eq "NS_NOTIFY_OP" ) {		#RFC1996
			if ( ref $self-&gt;{NotifyHandler} eq "CODE" ) {
				( $rcode, $ans, $auth, $add, $headermask ) =
					&amp;{$self-&gt;{NotifyHandler}}( $qname, $qclass, $qtype, $peerhost, $query, $conn );
			} else {
				$rcode = "NOTIMP";
				$headermask = {opcode =&gt; "NS_NOTIFY_OP"};
			}

		} else {
			print "ERROR: opcode $opcode unsupported\n" if $self-&gt;{Verbose};
			$rcode = "FORMERR";
		}

		if ( !defined($rcode) ) {
			print "remaining silent\n" if $self-&gt;{Verbose};
			return undef;
		}
		print "$rcode\n" if $self-&gt;{Verbose};

		$reply-&gt;header-&gt;rcode($rcode);

		$reply-&gt;push( "answer",	    @$ans )  if $ans;
		$reply-&gt;push( "authority",  @$auth ) if $auth;
		$reply-&gt;push( "additional", @$add )  if $add;
	}

	if ( !defined($headermask) ) {
		$reply-&gt;header-&gt;ra(1);
		$reply-&gt;header-&gt;ad(0);
	} else {
		my $op = $headermask-&gt;{opcode};
		$reply-&gt;header-&gt;opcode($op) if $op &amp;&amp; defined $Net::DNS::opcodesbyname{$op};

		$reply-&gt;header-&gt;aa(1) if $headermask-&gt;{aa};
		$reply-&gt;header-&gt;ra(1) if $headermask-&gt;{ra};
		$reply-&gt;header-&gt;ad(1) if $headermask-&gt;{ad};
	}

	$reply-&gt;header-&gt;cd( $query-&gt;header-&gt;cd );
	$reply-&gt;header-&gt;rd( $query-&gt;header-&gt;rd );
	$reply-&gt;header-&gt;id( $query-&gt;header-&gt;id );

	$reply-&gt;header-&gt;print if $self-&gt;{Verbose} &amp;&amp; defined $headermask;

	return $reply;
}

#------------------------------------------------------------------------------
# readfromtcp - read from a TCP client
#------------------------------------------------------------------------------

sub readfromtcp {
	my ( $self, $sock ) = @_;
	return -1 unless defined $self-&gt;{_tcp}{$sock};
	my $peer = $self-&gt;{_tcp}{$sock}{peer};
	my $buf;
	my $charsread = $sock-&gt;sysread( $buf, 16384 );
	$self-&gt;{_tcp}{$sock}{inbuffer} .= $buf;
	$self-&gt;{_tcp}{$sock}{timeout} = time() + $self-&gt;{IdleTimeout};	  # Reset idle timer
	print "Received $charsread octets from $peer\n" if $self-&gt;{Verbose};

	if ( $charsread == 0 ) {				# 0 octets means socket has closed
		print "Connection to $peer closed or lost.\n" if $self-&gt;{Verbose};
		$self-&gt;{select}-&gt;remove($sock);
		$sock-&gt;close();
		delete $self-&gt;{_tcp}{$sock};
		return $charsread;
	}
	return $charsread;
}

#------------------------------------------------------------------------------
# tcp_connection - Handle a TCP connection.
#------------------------------------------------------------------------------

sub tcp_connection {
	my ( $self, $sock ) = @_;

	if ( not $self-&gt;{_tcp}{$sock} ) {

		# We go here if we are called with a listener socket.
		my $client = $sock-&gt;accept;
		if ( not defined $client ) {
			print "TCP connection closed by peer before we could accept it.\n" if $self-&gt;{Verbose};
			return 0;
		}
		my $peerport = $client-&gt;peerport;
		my $peerhost = $client-&gt;peerhost;

		print "TCP connection from $peerhost:$peerport\n" if $self-&gt;{Verbose};
		$client-&gt;blocking(0);
		$self-&gt;{_tcp}{$client}{peer}	= "tcp:" . $peerhost . ":" . $peerport;
		$self-&gt;{_tcp}{$client}{state}	= STATE_ACCEPTED;
		$self-&gt;{_tcp}{$client}{socket}	= $client;
		$self-&gt;{_tcp}{$client}{timeout} = time() + $self-&gt;{IdleTimeout};
		$self-&gt;{select}-&gt;add($client);

		# After we accepted we will look at the socket again
		# to see if there is any data there. ---Olaf
		$self-&gt;loop_once(0);
	} else {

		# We go here if we are called with a client socket
		my $peer = $self-&gt;{_tcp}{$sock}{peer};

		if ( $self-&gt;{_tcp}{$sock}{state} == STATE_ACCEPTED ) {
			if ( not $self-&gt;{_tcp}{$sock}{inbuffer} =~ s/^(..)//s ) {
				return;				# Still not 2 octets ready
			}
			my $msglen = unpack( "n", $1 );
			print "Removed 2 octets from the input buffer from $peer.\n"
					. "$peer said his query contains $msglen octets.\n"
					if $self-&gt;{Verbose};
			$self-&gt;{_tcp}{$sock}{state}	  = STATE_GOT_LENGTH;
			$self-&gt;{_tcp}{$sock}{querylength} = $msglen;
		}

		# Not elsif, because we might already have all the data
		if ( $self-&gt;{_tcp}{$sock}{state} == STATE_GOT_LENGTH ) {

			# return if not all data has been received yet.
			return if $self-&gt;{_tcp}{$sock}{querylength} &gt; length $self-&gt;{_tcp}{$sock}{inbuffer};

			my $qbuf = substr( $self-&gt;{_tcp}{$sock}{inbuffer}, 0, $self-&gt;{_tcp}{$sock}{querylength} );
			substr( $self-&gt;{_tcp}{$sock}{inbuffer}, 0, $self-&gt;{_tcp}{$sock}{querylength} ) = "";
			my $query = new Net::DNS::Packet( \$qbuf );
			my $conn  = {
				sockhost =&gt; $sock-&gt;sockhost(),
				sockport =&gt; $sock-&gt;sockport(),
				peerhost =&gt; $sock-&gt;peerhost(),
				peerport =&gt; $sock-&gt;peerport()};
			my $reply = $self-&gt;make_reply( $query, $sock-&gt;peerhost, $conn );
			if ( not defined $reply ) {
				print "I couldn't create a reply for $peer. Closing socket.\n"
						if $self-&gt;{Verbose};
				$self-&gt;{select}-&gt;remove($sock);
				$sock-&gt;close();
				delete $self-&gt;{_tcp}{$sock};
				return;
			}
			my $reply_data = $reply-&gt;data;
			my $len	       = length $reply_data;
			$self-&gt;{_tcp}{$sock}{outbuffer} = pack( "n", $len ) . $reply_data;
			print "Queued ", length $self-&gt;{_tcp}{$sock}{outbuffer}, " octets to $peer\n"
					if $self-&gt;{Verbose};

			# We are done.
			$self-&gt;{_tcp}{$sock}{state} = STATE_SENDING;
		}
	}
}

#------------------------------------------------------------------------------
# udp_connection - Handle a UDP connection.
#------------------------------------------------------------------------------

sub udp_connection {
	my ( $self, $sock ) = @_;

	my $buf = "";

	$sock-&gt;recv( $buf, &amp;Net::DNS::PACKETSZ );
	my ( $peerhost, $peerport, $sockhost ) = ( $sock-&gt;peerhost, $sock-&gt;peerport, $sock-&gt;sockhost );
	unless ( defined $peerhost &amp;&amp; defined $peerport ) {
		print "the Peer host and sock host appear to be undefined: bailing out of handling the UDP connection"
				if $self-&gt;{Verbose};
		return;
	}


	print "UDP connection from $peerhost:$peerport to $sockhost\n" if $self-&gt;{Verbose};

	my ( $query, $err ) = new Net::DNS::Packet( \$buf, $self-&gt;{Verbose} );
	if ( !defined($query) ) {
		print "Error interpreting query: $err\n" if $self-&gt;{Verbose};
		return;
	}
	my $conn = {
		sockhost =&gt; $sock-&gt;sockhost,
		sockport =&gt; $sock-&gt;sockport,
		peerhost =&gt; $sock-&gt;peerhost,
		peerport =&gt; $sock-&gt;peerport
		};
	my $reply = $self-&gt;make_reply( $query, $peerhost, $conn ) || return;
	my $max_len = $self-&gt;max_udp_len($query);
	print "Maximum reply length as advertised in EDNS from $peerhost:$peerport: $max_len\n" if $self-&gt;{Verbose};
	$reply-&gt;truncate($max_len) if $self-&gt;{Truncate};
	local $| = 1 if $self-&gt;{Verbose};
	print "Writing response - " if $self-&gt;{Verbose};

	if ( $sock-&gt;send( $reply-&gt;data ) ) {			#
		print "done\n" if $self-&gt;{Verbose};
	} else {
		print "failed to send reply: $!\n" if $self-&gt;{Verbose};
	}
}


sub max_udp_len {
	my ( $self, $query ) = @_;

	for my $rr ( $query-&gt;additional ) {
		return $rr-&gt;size if $rr-&gt;type eq 'OPT';
	}

	return 512;
}


sub get_open_tcp {
	my $self = shift;
	return keys %{$self-&gt;{_tcp}};
}


#------------------------------------------------------------------------------
# loop_once - Just check "once" on sockets already set up
#------------------------------------------------------------------------------

# This function might not actually return immediately. If an AXFR request is
# coming in which will generate a huge reply, we will not relinquish control
# until our outbuffers are empty.

#
#  NB  this method may be subject to change and is therefore left 'undocumented'
#

sub loop_once {
	my ( $self, $timeout ) = @_;

	print ";loop_once called with timeout: " . ( defined($timeout) ? $timeout : "undefined" ) . "\n"
			if $self-&gt;{Verbose} &amp;&amp; $self-&gt;{Verbose} &gt; 4;
	foreach my $sock ( keys %{$self-&gt;{_tcp}} ) {

		# There is TCP traffic to handle
		$timeout = 0.1 if $self-&gt;{_tcp}{$sock}{outbuffer};
	}
	my @ready = $self-&gt;{select}-&gt;can_read($timeout);

	foreach my $sock (@ready) {
		my $protonum = $sock-&gt;protocol;

		# This is a weird and nasty hack. Although not incorrect,
		# I just don't know why -&gt;protocol won't tell me the protocol
		# on a connected socket. --robert
		$protonum = getprotobyname('tcp') if not defined $protonum and $self-&gt;{_tcp}{$sock};

		my $proto = getprotobynumber($protonum);
		if ( !$proto ) {
			print "ERROR: connection with unknown protocol\n"
					if $self-&gt;{Verbose};
		} elsif ( lc($proto) eq "tcp" ) {

			$self-&gt;readfromtcp($sock)
					&amp;&amp; $self-&gt;tcp_connection($sock);
		} elsif ( lc($proto) eq "udp" ) {
			$self-&gt;udp_connection($sock);
		} else {
			print "ERROR: connection with unsupported protocol $proto\n"
					if $self-&gt;{Verbose};
		}
	}
	my $now = time();

	# Lets check if any of our TCP clients has pending actions.
	# (outbuffer, timeout)
	foreach my $s ( keys %{$self-&gt;{_tcp}} ) {
		my $sock = $self-&gt;{_tcp}{$s}{socket};
		if ( $self-&gt;{_tcp}{$s}{outbuffer} ) {

			# If we have buffered output, then send as much as the OS will accept
			# and wait with the rest
			my $len = length $self-&gt;{_tcp}{$s}{outbuffer};
			my $charssent = $sock-&gt;syswrite( $self-&gt;{_tcp}{$s}{outbuffer} ) || 0;
			print "Sent $charssent of $len octets to ", $self-&gt;{_tcp}{$s}{peer}, ".\n"
					if $self-&gt;{Verbose};
			substr( $self-&gt;{_tcp}{$s}{outbuffer}, 0, $charssent ) = "";
			if ( length $self-&gt;{_tcp}{$s}{outbuffer} == 0 ) {
				delete $self-&gt;{_tcp}{$s}{outbuffer};
				$self-&gt;{_tcp}{$s}{state} = STATE_ACCEPTED;
				if ( length $self-&gt;{_tcp}{$s}{inbuffer} &gt;= 2 ) {

					# See if the client has send us enough data to process the
					# next query.
					# We do this here, because we only want to process (and buffer!!)
					# a single query at a time, per client. If we allowed a STATE_SENDING
					# client to have new requests processed. We could be easilier
					# victims of DoS (client sending lots of queries and never reading
					# from it's socket).
					# Note that this does not disable serialisation on part of the
					# client. The split second it should take for us to lookip the
					# next query, is likely faster than the time it takes to
					# send the response... well, unless it's a lot of tiny queries,
					# in which case we will be generating an entire TCP packet per
					# reply. --robert
					$self-&gt;tcp_connection( $self-&gt;{_tcp}{$s}{socket} );
				}
			}
			$self-&gt;{_tcp}{$s}{timeout} = time() + $self-&gt;{IdleTimeout};
		} else {

			# Get rid of idle clients.
			my $timeout = $self-&gt;{_tcp}{$s}{timeout};
			if ( $timeout - $now &lt; 0 ) {
				print $self-&gt;{_tcp}{$s}{peer}, " has been idle for too long and will be disconnected.\n"
						if $self-&gt;{Verbose};
				$self-&gt;{select}-&gt;remove($sock);
				$sock-&gt;close();
				delete $self-&gt;{_tcp}{$s};
			}
		}
	}
}

#------------------------------------------------------------------------------
# main_loop - Main nameserver loop.
#------------------------------------------------------------------------------

sub main_loop {
	my $self = shift;

	while (1) {
		print "Waiting for connections...\n" if $self-&gt;{Verbose};

		# You really need an argument otherwise you'll be burning CPU.
		$self-&gt;loop_once(10);
	}
}


1;
__END__


=head1 METHODS

=head2 new

    my $ns = new Net::DNS::Nameserver(
	LocalAddr	=&gt; "10.1.2.3",
	LocalPort	=&gt; "5353",
	ReplyHandler	=&gt; \&amp;reply_handler,
	Verbose		=&gt; 1
	);



    my $ns = new Net::DNS::Nameserver(
	LocalAddr	=&gt; ['::1' , '127.0.0.1' ],
	LocalPort	=&gt; "5353",
	ReplyHandler	=&gt; \&amp;reply_handler,
	Verbose		=&gt; 1,
	Truncate	=&gt; 0
	);

Creates a nameserver object.  Attributes are:

    LocalAddr		IP address on which to listen.	Defaults to INADDR_ANY.
    LocalPort		Port on which to listen.	Defaults to 53.
    ReplyHandler	Reference to reply-handling
			subroutine			Required.
    NotifyHandler	Reference to reply-handling
			subroutine for queries with
			opcode NS_NOTIFY (RFC1996)
    Verbose		Print info about received
			queries.			Defaults to 0 (off).
    Truncate		Truncates UDP packets that
			are to big for the reply	Defaults to 1 (on)
    IdleTimeout		TCP clients are disconnected
			if they are idle longer than
			this duration.			Defaults to 120 (secs)

The LocalAddr attribute may alternatively be specified as a list of IP
addresses to listen to.

If IO::Socket::INET6 and Socket6 are available on the system you can
also list IPv6 addresses and the default is '0' (listen on all interfaces on
IPv6 and IPv4);


The ReplyHandler subroutine is passed the query name, query class,
query type and optionally an argument containing the peerhost, the
incoming query, and the name of the incoming socket (sockethost). It
must either return the response code and references to the answer,
authority, and additional sections of the response, or undef to leave
the query unanswered.  Common response codes are:

    NOERROR	No error
    FORMERR	Format error
    SERVFAIL	Server failure
    NXDOMAIN	Non-existent domain (name doesn't exist)
    NOTIMP	Not implemented
    REFUSED	Query refused

For advanced usage it may also contain a headermask containing an
hashref with the settings for the C&lt;aa&gt;, C&lt;ra&gt;, and C&lt;ad&gt;
header bits. The argument is of the form
C&lt;&lt; { ad =&gt; 1, aa =&gt; 0, ra =&gt; 1 } &gt;&gt;.


See RFC 1035 and the IANA dns-parameters file for more information:

  ftp://ftp.rfc-editor.org/in-notes/rfc1035.txt
  http://www.isi.edu/in-notes/iana/assignments/dns-parameters

The nameserver will listen for both UDP and TCP connections.  On
Unix-like systems, the program will probably have to run as root
to listen on the default port, 53.	A non-privileged user should
be able to listen on ports 1024 and higher.

Packet Truncation is new functionality for
$Net::DNS::Nameserver::VERSION&gt;830 and uses the
Net::DNS::Packet::truncate method with a size determinde by the
advertised EDNS0 size in the query, or 512 if EDNS0 is not advertised
in the query. Only UDP replies are truncated. If you want to do packet
runcation yourself you should set Truncate to 0 and use the truncate
method on the reply packet in the code you use for the ReplyHandler.

Returns a Net::DNS::Nameserver object, or undef if the object
couldn't be created.

See L&lt;/EXAMPLE&gt; for an example.

=head2 main_loop

    $ns-&gt;main_loop;

Start accepting queries. Calling main_loop never returns.

=cut

=head2 loop_once

    $ns-&gt;loop_once( [TIMEOUT_IN_SECONDS] );

Start accepting queries, but returns. If called without a parameter,
the call will not return until a request has been received (and
replied to). If called with a number, that number specifies how many
seconds (even fractional) to maximum wait before returning. If called
with 0 it will return immediately unless there's something to do.

Handling a request and replying obviously depends on the speed of
ReplyHandler. Assuming ReplyHandler is super fast, loop_once should spend
just a fraction of a second, if called with a timeout value of 0 seconds.
One exception is when an AXFR has requested a huge amount of data that
the OS is not ready to receive in full. In that case, it will keep
running through a loop (while servicing new requests) until the reply
has been sent.

In case loop_once accepted a TCP connection it will immediatly check
if there is data to be read from the socket. If not it will return and
you will have to call loop_once() again to check if there is any data
waiting on the socket to be processed. In most cases you will have to
count on calling "loop_once" twice.

A code fragment like:

    $ns-&gt;loop_once(10);
    while( $ns-&gt;get_open_tcp() ){
	$ns-&gt;loop_once(0);
    }

Would wait for 10 seconds for the initial connection and would then
process all TCP sockets until none is left.

=head2 get_open_tcp

In scalar context returns the number of TCP connections for which state
is maintained. In array context it returns IO::Socket objects, these could
be useful for troubleshooting but be careful using them.

=head1 EXAMPLE

The following example will listen on port 5353 and respond to all queries
for A records with the IP address 10.1.2.3.	 All other queries will be
answered with NXDOMAIN.	 Authority and additional sections are left empty.
The $peerhost variable catches the IP address of the peer host, so that
additional filtering on its basis may be applied.

    #!/usr/bin/perl

    use strict;
    use warnings;
    use Net::DNS::Nameserver;

    sub reply_handler {
	my ($qname, $qclass, $qtype, $peerhost,$query,$conn) = @_;
	my ($rcode, @ans, @auth, @add);

	print "Received query from $peerhost to ". $conn-&gt;{sockhost}. "\n";
	$query-&gt;print;

	if ($qtype eq "A" &amp;&amp; $qname eq "foo.example.com" ) {
		my ($ttl, $rdata) = (3600, "10.1.2.3");
		my $rr = new Net::DNS::RR("$qname $ttl $qclass $qtype $rdata");
		push @ans, $rr;
		$rcode = "NOERROR";
	}elsif( $qname eq "foo.example.com" ) {
		$rcode = "NOERROR";

	}else{
		$rcode = "NXDOMAIN";
	}

	# mark the answer as authoritive (by setting the 'aa' flag
	return ($rcode, \@ans, \@auth, \@add, { aa =&gt; 1 });
    }

    my $ns = new Net::DNS::Nameserver(
	LocalPort    =&gt; 5353,
	ReplyHandler =&gt; \&amp;reply_handler,
	Verbose	     =&gt; 1
	) || die "couldn't create nameserver object\n";

    $ns-&gt;main_loop;

=head1 BUGS

Limitations in perl 5.8.6 makes it impossible to guarantee that
replies to UDP queries from Net::DNS::Nameserver are sent from the
IP-address they were received on. This is a problem for machines with
multiple IP-addresses and causes violation of RFC2181 section 4.
Thus a UDP socket created listening to INADDR_ANY (all available
IP-addresses) will reply not necessarily with the source address being
the one to which the request was sent, but rather with the address that
the operating system choses. This is also often called "the closest
address". This should really only be a problem on a server which has
more than one IP-address (besides localhost - any experience with IPv6
complications here, would be nice). If this is a problem for you, a
work-around would be to not listen to INADDR_ANY but to specify each
address that you want this module to listen on. A separate set of
sockets will then be created for each IP-address.

=head1 COPYRIGHT

Copyright (c)1997-2002 Michael Fuhr.

Portions Copyright (c)2002-2004 Chris Reinhardt.

Portions Copyright (c)2005-2009 O.M, Kolkman, RIPE NCC.

Portions Copyright (c)2005 Robert Martin-Legene.

All rights reserved.

This program is free software; you may redistribute it and/or
modify it under the same terms as Perl itself.

=head1 SEE ALSO

L&lt;perl&gt;, L&lt;Net::DNS&gt;, L&lt;Net::DNS::Resolver&gt;, L&lt;Net::DNS::Packet&gt;,
L&lt;Net::DNS::Update&gt;, L&lt;Net::DNS::Header&gt;, L&lt;Net::DNS::Question&gt;,
L&lt;Net::DNS::RR&gt;, RFC 1035

=cut
</pre></body></html>