简单的DNS服务器
提供一个简单的可以查询域名和反向查询的DNS服务器。
dig命令主要用来从 DNS 域名服务器查询主机地址信息。
查找www.baidu.com的ip (A记录):
命令:dig @127.0.0.1 www.baidu.com
根据ip查找对应域名 (PTR记录):
命令:dig @127.0.0.1 -x 220.181.38.150
源码 :
package main
import (
"fmt"
"net"
"golang.org/x/net/dns/dnsmessage"
)
func main() {
conn, err := net.ListenUDP("udp", &net.UDPAddr{Port: 53})
if err != nil {
panic(err)
}
defer conn.Close()
fmt.Println("Listing ...")
for {
buf := make([]byte, 512)
_, addr, _ := conn.ReadFromUDP(buf)
var msg dnsmessage.Message
if err := msg.Unpack(buf); err != nil {
fmt.Println(err)
continue
}
go ServerDNS(addr, conn, msg)
}
}
// address books
var (
addressBookOfA = map[string][4]byte{
"www.baidu.com.": [4]byte{220, 181, 38, 150},
}
addressBookOfPTR = map[string]string{
"150.38.181.220.in-addr.arpa.": "www.baidu.com.",
}
)
// ServerDNS serve
func ServerDNS(addr *net.UDPAddr, conn *net.UDPConn, msg dnsmessage.Message) {
// query info
if len(msg.Questions) < 1 {
return
}
question := msg.Questions[0]
var (
queryTypeStr = question.Type.String()
queryNameStr = question.Name.String()
queryType = question.Type
queryName, _ = dnsmessage.NewName(queryNameStr)
)
fmt.Printf("[%s] queryName: [%s]
", queryTypeStr, queryNameStr)
// find record
var resource dnsmessage.Resource
switch queryType {
case dnsmessage.TypeA:
if rst, ok := addressBookOfA[queryNameStr]; ok {
resource = NewAResource(queryName, rst)
} else {
fmt.Printf("not fount A record queryName: [%s]
", queryNameStr)
Response(addr, conn, msg)
return
}
case dnsmessage.TypePTR:
if rst, ok := addressBookOfPTR[queryName.String()]; ok {
resource = NewPTRResource(queryName