Introduction to DNS
easy 25 minDNS is the distributed database that turns names such as www.example.com into addresses computers can connect to.
A small resolver with records, aliases and a TTL cache
Read it, run it, change a line and run it again.
Loading editor…
It answers from an in-memory zone so that it runs anywhere. On a real machine, socket.getaddrinfo gives you addresses, and a library such as dnspython gives you record types and TTLs.
The same in TypeScript
import { Resolver } from "node:dns/promises";const resolver = new Resolver();resolver.setServers(["1.1.1.1", "8.8.8.8"]); // two resolvers for redundancytype Cached = { addresses: string[]; expires: number };const cache = new Map<string, Cached>();/** IPv4 addresses, cached for the TTL the record really has. */async function addresses(name: string): Promise<string[]> { const hit = cache.get(name); if (hit && hit.expires > Date.now()) return hit.addresses; const records = await resolver.resolve4(name, { ttl: true }); const ttl = Math.min(...records.map((r) => r.ttl)); const found = records.map((r) => r.address); cache.set(name, { addresses: found, expires: Date.now() + ttl * 1000 }); return found;}/** Every kind we care about; a missing kind is simply absent. */async function everything(name: string) { const [a, aaaa, mx, txt, ns] = await Promise.allSettled([ addresses(name), resolver.resolve6(name), resolver.resolveMx(name).then((m) => m.sort((x, y) => x.priority - y.priority)), resolver.resolveTxt(name), resolver.resolveNs(name), ]); return Object.fromEntries( Object.entries({ a, aaaa, mx, txt, ns }) .filter(([, r]) => r.status === "fulfilled") .map(([k, r]) => [k, (r as PromiseFulfilledResult<unknown>).value]), );}async function names(ip: string) { return resolver.reverse(ip); // PTR}console.log(await everything("example.com"));The same in Go
package mainimport ( "context" "fmt" "net" "sort" "time")// A resolver that asks a chosen server over the network and port Go picked.func newResolver(server string) *net.Resolver { return &net.Resolver{ PreferGo: true, Dial: func(ctx context.Context, network, _ string) (net.Conn, error) { d := net.Dialer{Timeout: 3 * time.Second} return d.DialContext(ctx, network, net.JoinHostPort(server, "53")) }, }}func main() { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() r := newResolver("1.1.1.1") if ips, err := r.LookupIP(ctx, "ip4", "example.com"); err == nil { fmt.Println("A", ips) } if ips, err := r.LookupIP(ctx, "ip6", "example.com"); err == nil { fmt.Println("AAAA", ips) } if mx, err := r.LookupMX(ctx, "example.com"); err == nil { sort.Slice(mx, func(i, j int) bool { return mx[i].Pref < mx[j].Pref }) for _, m := range mx { fmt.Println("MX", m.Pref, m.Host) } } if txt, err := r.LookupTXT(ctx, "example.com"); err == nil { fmt.Println("TXT", txt) } if ns, err := r.LookupNS(ctx, "example.com"); err == nil { for _, n := range ns { fmt.Println("NS", n.Host) } } // Go's standard library does not return the TTL: do not invent one.}The same in Java
import java.net.*;import java.util.*;import javax.naming.*;import javax.naming.directory.*;public class DnsLookup { private final DirContext dns; DnsLookup(String server) throws NamingException { var env = new Hashtable<String, String>(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory"); env.put(Context.PROVIDER_URL, "dns://" + server); dns = new InitialDirContext(env); } List<String> records(String name, String type) throws NamingException { Attribute found = dns.getAttributes(name, new String[] {type}).get(type); var out = new ArrayList<String>(); if (found != null) { var all = found.getAll(); while (all.hasMore()) out.add(all.next().toString()); } return out; } record Mx(int preference, String host) {} List<Mx> mail(String name) throws NamingException { return records(name, "MX").stream() .map(v -> v.split(" ", 2)) .map(p -> new Mx(Integer.parseInt(p[0]), p[1])) .sorted(Comparator.comparingInt(Mx::preference)) .toList(); } public static void main(String[] args) throws Exception { var d = new DnsLookup("1.1.1.1"); for (var type : List.of("A", "AAAA", "TXT", "NS")) { System.out.println(type + " " + d.records("example.com", type)); } System.out.println("MX " + d.mail("example.com")); System.out.println("PTR " + InetAddress.getByName("1.1.1.1").getCanonicalHostName()); }}