Learn more about Russian war crimes in Ukraine.

How to write a DNS server in Go

Here’s a DNS server written in Go. It uses the package github.com/miekg/dns, which is an alternative to the standard library’s DNS stuff, and also lets you implement a DNS server rather than just a client. The example DNS server below only knows how to answer A queries, and for these, it only knows the IP addresses of two domains.

package main

import (

var domainsToAddresses map[string]string = map[string]string{
	"google.com.": "",
	"jameshfisher.com.": "",

type handler struct{}
func (this *handler) ServeDNS(w dns.ResponseWriter, r *dns.Msg) {
	msg := dns.Msg{}
	switch r.Question[0].Qtype {
	case dns.TypeA:
		msg.Authoritative = true
		domain := msg.Question[0].Name
		address, ok := domainsToAddresses[domain]
		if ok {
			msg.Answer = append(msg.Answer, &dns.A{
				Hdr: dns.RR_Header{ Name: domain, Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: 60 },
				A: net.ParseIP(address),

func main() {
	srv := &dns.Server{Addr: ":" + strconv.Itoa(53), Net: "udp"}
	srv.Handler = &handler{}
	if err := srv.ListenAndServe(); err != nil {
		log.Fatalf("Failed to set udp listener %s\n", err.Error())

Example usage:

$ sudo go run main.go &
$ dig @ jameshfisher.com

; <<>> DiG 9.8.3-P1 <<>> @ jameshfisher.com
; (1 server found)
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 25014
;; flags: qr aa rd; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0
;; WARNING: recursion requested but not available

;jameshfisher.com.		IN	A

jameshfisher.com.	60	IN	A

;; Query time: 0 msec
;; WHEN: Sun Aug 27 00:27:06 2017
;; MSG SIZE  rcvd: 66

This program could be extended with more custom logic. For example, at Pusher (the company I work for), we could operate a DNS server which resolves a Pusher app’s domain to the cluster that the app is on.

What can computers do? What are the limits of mathematics? And just how busy can a busy beaver be? This year, I’m writing Busy Beavers, a unique interactive book on computability theory. You and I will take a practical and modern approach to answering these questions — or at least learning why some questions are unanswerable!

It’s only $19, and you can get 50% off if you find the discount code ... Not quite. Hackers use the console!

After months of secret toil, I and Andrew Carr released Everyday Data Science, a unique interactive online course! You’ll make the perfect glass of lemonade using Thompson sampling. You’ll lose weight with differential equations. And you might just qualify for the Olympics with a bit of statistics!

It’s $29, but you can get 50% off if you find the discount code ... Not quite. Hackers use the console!

More by Jim

Tagged . All content copyright James Fisher 2017. This post is not associated with my employer. Found an error? Edit this page.