{
    "mode": "perldoc",
    "parameter": "Net::DNS::Nameserver",
    "section": "",
    "url": "https://www.chedong.com/phpMan.php/perldoc/Net%3A%3ADNS%3A%3ANameserver/json",
    "generated": "2026-07-05T13:45:55Z",
    "synopsis": "use Net::DNS::Nameserver;\nmy $nameserver = Net::DNS::Nameserver->new(\nLocalAddr       => ['::1' , '127.0.0.1'],\nZoneFile        => \"filename\"\n);\nmy $nameserver = Net::DNS::Nameserver->new(\nLocalAddr       => '10.1.2.3',\nLocalPort       => 5353,\nReplyHandler    => \\&replyhandler\n);",
    "sections": {
        "NAME": {
            "content": "Net::DNS::Nameserver - DNS server class\n",
            "subsections": []
        },
        "SYNOPSIS": {
            "content": "use Net::DNS::Nameserver;\n\nmy $nameserver = Net::DNS::Nameserver->new(\nLocalAddr       => ['::1' , '127.0.0.1'],\nZoneFile        => \"filename\"\n);\n\nmy $nameserver = Net::DNS::Nameserver->new(\nLocalAddr       => '10.1.2.3',\nLocalPort       => 5353,\nReplyHandler    => \\&replyhandler\n);\n",
            "subsections": []
        },
        "DESCRIPTION": {
            "content": "Net::DNS::Nameserver offers a simple mechanism for instantiation of customised DNS server\nobjects intended to provide test responses to queries emanating from a client resolver.\n\nIt is not, nor will it ever be, a general-purpose DNS nameserver implementation.\n\nSee \"EXAMPLE\" for an example.\n",
            "subsections": []
        },
        "METHODS": {
            "content": "new\n$nameserver = Net::DNS::Nameserver->new(\nLocalAddr       => ['::1' , '127.0.0.1'],\nZoneFile        => \"filename\"\n);\n\n$nameserver = Net::DNS::Nameserver->new(\nLocalAddr       => '10.1.2.3',\nLocalPort       => 5353,\nReplyHandler    => \\&replyhandler,\nVerbose         => 1,\nTruncate        => 0\n);\n\nReturns a Net::DNS::Nameserver object, or undef if the object could not be created.\n\nEach instance is configured using the following optional arguments:\n\nLocalAddr           IP address on which to listen   Defaults to loopback address\nLocalPort           Port on which to listen         Defaults to 5353\nZoneFile            Name of file containing RRs\naccessed using the default\nreply-handling subroutine\nReplyHandler        Reference to customised\nreply-handling subroutine\nNotifyHandler       Reference to reply-handling\nsubroutine for queries with\nopcode NOTIFY (RFC1996)\nUpdateHandler       Reference to reply-handling\nsubroutine for queries with\nopcode UPDATE (RFC2136)\nVerbose             Report internal activity        Defaults to 0 (off)\nTruncate            Truncates UDP packets that\nare too big for the reply       Defaults to 1 (on)\nIdleTimeout         TCP clients are disconnected\nif they are idle longer than\nthis duration                   Defaults to 120 (secs)\n\nThe LocalAddr attribute may alternatively be specified as a list of IP addresses to listen to.\nIf the IO::Socket::IP library package is available on the system this may also include IPv6\naddresses.\n\nThe ReplyHandler subroutine is passed the query name, query class, query type, peerhost, query\nrecord, and connection descriptor. It must either return the response code and references to the\nanswer, authority, and additional sections of the response, or undef to leave the query\nunanswered. Common response codes are:\n\nNOERROR     No error\nFORMERR     Format error\nSERVFAIL    Server failure\nNXDOMAIN    Non-existent domain (name doesn't exist)\nNOTIMP      Not implemented\nREFUSED     Query refused\n\nFor advanced usage it may also contain a headermask containing an hashref with the settings for\nthe \"aa\", \"ra\", and \"ad\" header bits. The argument is of the form \"{ ad => 1, aa => 0, ra => 1\n}\".\n\nEDNS options may be specified in a similar manner using optionmask \"{ $optioncode => $value,\n$optionname => $value }\".\n\nSee RFC 1035 and the IANA dns-parameters file for more information:\n\nftp://ftp.rfc-editor.org/in-notes/rfc1035.txt\nhttp://www.isi.edu/in-notes/iana/assignments/dns-parameters\n\nThe nameserver will listen for both UDP and TCP connections. On Unix-like systems, unprivileged\nusers are denied access to ports below 1024.\n\nUDP reply truncation functionality was introduced in VERSION 830. The size limit is determined\nby the EDNS0 size advertised in the query, otherwise 512 is used. If you want to do packet\ntruncation yourself you should set \"Truncate\" to 0 and truncate the reply packet in the code of\nthe ReplyHandler.\n\nSee \"EXAMPLE\" for an example.\n\nmainloop\n$ns->mainloop;\n\nStart accepting queries. Calling mainloop never returns.\n\nlooponce\n$ns->looponce( [TIMEOUTINSECONDS] );\n\nStart accepting queries, but returns. If called without a parameter, the call will not return\nuntil a request has been received (and replied to). Otherwise, the parameter specifies the\nmaximum time to wait for a request. A zero timeout forces an immediate return if there is\nnothing to do.\n\nHandling a request and replying obviously depends on the speed of ReplyHandler. Assuming a fast\nReplyHandler, looponce should spend just a fraction of a second, if called with a timeout value\nof 0.0 seconds. One exception is when an AXFR has requested a huge amount of data that the OS is\nnot ready to receive in full. In that case, it will remain in a loop (while servicing new\nrequests) until the reply has been sent.\n\nIn case looponce accepted a TCP connection it will immediately check if there is data to be\nread from the socket. If not it will return and you will have to call looponce() again to check\nif there is any data waiting on the socket to be processed. In most cases you will have to count\non calling \"looponce\" twice.\n\nA code fragment like:\n\n$ns->looponce(10);\nwhile( $ns->getopentcp() ){\n$ns->looponce(0);\n}\n\nWould wait for 10 seconds for the initial connection and would then process all TCP sockets\nuntil none is left.\n\ngetopentcp\nIn scalar context returns the number of TCP connections for which state is maintained. In array\ncontext it returns IO::Socket objects, these could be useful for troubleshooting but be careful\nusing them.\n",
            "subsections": []
        },
        "EXAMPLE": {
            "content": "The following example will listen on port 5353 and respond to all queries for A records with the\nIP address 10.1.2.3. All other queries will be answered with NXDOMAIN. Authority and additional\nsections are left empty. The $peerhost variable catches the IP address of the peer host, so that\nadditional filtering on its basis may be applied.\n\n#!/usr/bin/perl\n\nuse strict;\nuse warnings;\nuse Net::DNS::Nameserver;\n\nsub replyhandler {\nmy ( $qname, $qclass, $qtype, $peerhost, $query, $conn ) = @;\nmy ( $rcode, @ans, @auth, @add );\n\nprint \"Received query from $peerhost to \" . $conn->{sockhost} . \"\\n\";\n$query->print;\n\nif ( $qtype eq \"A\" && $qname eq \"foo.example.com\" ) {\nmy ( $ttl, $rdata ) = ( 3600, \"10.1.2.3\" );\nmy $rr = Net::DNS::RR->new(\"$qname $ttl $qclass $qtype $rdata\");\npush @ans, $rr;\n$rcode = \"NOERROR\";\n} elsif ( $qname eq \"foo.example.com\" ) {\n$rcode = \"NOERROR\";\n\n} else {\n$rcode = \"NXDOMAIN\";\n}\n\n# mark the answer as authoritative (by setting the 'aa' flag)\nmy $headermask = {aa => 1};\n\n# specify EDNS options  { option => value }\nmy $optionmask = {};\n\nreturn ( $rcode, \\@ans, \\@auth, \\@add, $headermask, $optionmask );\n}\n\n\nmy $ns = Net::DNS::Nameserver->new(\nLocalPort    => 5353,\nReplyHandler => \\&replyhandler,\nVerbose      => 1\n) || die \"couldn't create nameserver object\\n\";\n\n\n$ns->mainloop;\n",
            "subsections": []
        },
        "BUGS": {
            "content": "Limitations in perl make it impossible to guarantee that replies to UDP queries from\nNet::DNS::Nameserver are sent from the IP-address to which the query was directed. This is a\nproblem for machines with multiple IP-addresses and causes violation of RFC2181 section 4. Thus\na UDP socket created listening to INADDRANY (all available IP-addresses) will reply not\nnecessarily with the source address being the one to which the request was sent, but rather with\nthe address that the operating system chooses. This is also often called \"the closest address\".\nThis should really only be a problem on a server which has more than one IP-address (besides\nlocalhost - any experience with IPv6 complications here, would be nice). If this is a problem\nfor you, a work-around would be to not listen to INADDRANY but to specify each address that you\nwant this module to listen on. A separate set of sockets will then be created for each\nIP-address.\n",
            "subsections": []
        },
        "COPYRIGHT": {
            "content": "Copyright (c)2000 Michael Fuhr.\n\nPortions Copyright (c)2002-2004 Chris Reinhardt.\n\nPortions Copyright (c)2005 Robert Martin-Legene.\n\nPortions Copyright (c)2005-2009 O.M, Kolkman, RIPE NCC.\n\nPortions Copyright (c)2017 Dick Franks.\n\nAll rights reserved.\n",
            "subsections": []
        },
        "LICENSE": {
            "content": "Permission to use, copy, modify, and distribute this software and its documentation for any\npurpose and without fee is hereby granted, provided that the original copyright notices appear\nin all copies and that both copyright notice and this permission notice appear in supporting\ndocumentation, and that the name of the author not be used in advertising or publicity\npertaining to distribution of the software without specific prior written permission.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING\nBUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\nNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\nDAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n",
            "subsections": []
        },
        "SEE ALSO": {
            "content": "perl, Net::DNS, Net::DNS::Resolver, Net::DNS::Packet, Net::DNS::Update, Net::DNS::Header,\nNet::DNS::Question, Net::DNS::RR, RFC 1035\n",
            "subsections": []
        }
    },
    "summary": "Net::DNS::Nameserver - DNS server class",
    "flags": [],
    "examples": [
        "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 replyhandler {",
        "my ( $qname, $qclass, $qtype, $peerhost, $query, $conn ) = @;",
        "my ( $rcode, @ans, @auth, @add );",
        "print \"Received query from $peerhost to \" . $conn->{sockhost} . \"\\n\";",
        "$query->print;",
        "if ( $qtype eq \"A\" && $qname eq \"foo.example.com\" ) {",
        "my ( $ttl, $rdata ) = ( 3600, \"10.1.2.3\" );",
        "my $rr = Net::DNS::RR->new(\"$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 authoritative (by setting the 'aa' flag)",
        "my $headermask = {aa => 1};",
        "# specify EDNS options  { option => value }",
        "my $optionmask = {};",
        "return ( $rcode, \\@ans, \\@auth, \\@add, $headermask, $optionmask );",
        "my $ns = Net::DNS::Nameserver->new(",
        "LocalPort    => 5353,",
        "ReplyHandler => \\&replyhandler,",
        "Verbose      => 1",
        ") || die \"couldn't create nameserver object\\n\";",
        "$ns->mainloop;"
    ],
    "see_also": []
}