DNS協議Golang實現

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

DNS用戶端的實現還是用了Go語言,畢竟這個最熟悉。我的實現只是簡單的實現了發送DNS請求,解析響應內容這些功能,對於多線程並發等機制都沒有考慮。

我最先參考了《電腦網路》,上面提了一句,DNS請求就是發送一個UDP資料包,然後我就天真了,直接把網域名稱的字串用UDP發送了。結果就是沒有響應。

後來就老老實實的分析協議,協議的分析請參考上一篇文章《DNS協議分析》。

網域名稱伺服器選用了阿里提供的233.5.5.5,53連接埠。詳情可以查看阿里DNS官網。

先說一下Golang發送UDP資料報的方法。所有語言這塊兒好像都長差不多,我就不多介紹了。

service := "223.5.5.5:53"udpAddr, err := net.ResolveUDPAddr("udp", service)checkError(err)conn, err := net.DialUDP("udp", nil, udpAddr)checkError(err)_, err = conn.Write(out.Pack())checkError(err)buf := []byte{}buf = make([]byte, 512)n, err := conn.Read(buf[0:])checkError(err)

接著就是發送和接收要用到的訊息體,它由一個TransationID、Flags、查詢數Questions、Answer是響應數和查詢Question組成。查詢Question由網域名稱、類別、分類組成。查詢結果ANswer由查詢網域名稱、記錄類型、分類、資料長度和Primaryname組成。這些結構可以定義為:

type DnsMsg struct {Id                                 uint16Bits                               uint16Qdcount, Ancount, Nscount, Arcount uint16Questions                          []dnsQuestionAnswers                            []dnsAnswer}type dnsQuestion struct {Name   string `net:"domain-name"`Qtype  uint16Qclass uint16}type dnsAnswer struct {Name   uint16Qtype  uint16Qclass uint16QLive  uint32QLen   uint16CName  string `net:"domain-name"`}

DNS協議規定是兩個位元組的,都用uint16進行處理,Question裡面的Name和Answer裡面定義的CNAME應該定義成[]byte,但是為了方便查看,先定義成了字串,最後編碼的時候再處理就行了。

有了結構體,就可以為這些結構體賦值,然後將其編碼成位元組碼進行發送。編碼方法如下:

func (this *DnsMsg) Pack() []byte {bs := make([]byte, 12)binary.BigEndian.PutUint16(bs[0:2], this.Id)binary.BigEndian.PutUint16(bs[2:4], this.Bits)binary.BigEndian.PutUint16(bs[4:6], uint16(len(this.Questions)))binary.BigEndian.PutUint16(bs[6:8], this.Ancount)binary.BigEndian.PutUint16(bs[8:10], this.Nscount)binary.BigEndian.PutUint16(bs[10:12], this.Arcount)ds := strings.Split(this.Questions[0].Name, ".")for _, d := range ds {bs = append(bs, byte(len(d)))bs = append(bs, []byte(d)...)}bs = append(bs, 0)temp := make([]byte, 2)binary.BigEndian.PutUint16(temp, this.Questions[0].Qtype)bs = append(bs, temp...)binary.BigEndian.PutUint16(temp, this.Questions[0].Qclass)bs = append(bs, temp...)return bs}

DNS頭是固定的12個位元組,所以先bs := make([]byte, 12)申請12個位元組空間。接著,填充這些位元組。就是將結構體裡面的uint16轉成[]byte。這要用到binary包進行轉換。最後就是填充Question,要將網域名稱進行轉換。轉換剔除了網域名稱裡面的.,改成其後面部分長度的資訊,也就是把www.cyeam.com換成3www5cyeam3com0。轉換完成之後,還要添加一位0來表示結束。最後,再加上請求的類型和分類即可。

這些都請求成功之後,列印結果,終於能看到點東西了:一堆亂碼裡面有一些字母,能看得出來是我的網域名稱的CDN地址。

最後,就是解析響應內容。響應和請求格式是一樣的,區別就是最後比請求多了一些響應內容。

DNS頭的12個位元組和請求裡面是完全一樣的,返過來解析就可以了。需要注意兩點,響應的頭兩個位元組和請求的頭兩個位元組是完全一樣的,如果不一樣,忽略這個請求。還有,請求的時候ancount是0,這個代表響應數量,在響應裡面就會是找到的結果數。

查詢請求的Question也會在響應裡面,所以也需要進行解析。請求查詢時Question有可能是多個,這裡都處理了一下。從第13個位元組開始處理:

i := 13for ; j < int(res.Qdcount); j++ {domain_count := int(buf[i-1])question := dnsQuestion{}for buf[i] != 0 {if domain_count > 0 {question.Name += string(buf[i:i+domain_count]) + "."i += domain_countdomain_count = 0} else {domain_count = int(buf[i])i++}}i++question.Name = strings.TrimRight(question.Name, ".")question.Qtype = binary.BigEndian.Uint16(buf[i : i+2])question.Qclass = binary.BigEndian.Uint16(buf[i+2 : i+4])i += 4res.Questions[j] = question}

剩下的東西都是Answer。前5個部分都是固定長度,分別是2、2、2、4、2。

answer := dnsAnswer{}answer.Name = binary.BigEndian.Uint16(buf[i : i+2])i += 2answer.Qtype = binary.BigEndian.Uint16(buf[i : i+2])i += 2answer.Qclass = binary.BigEndian.Uint16(buf[i : i+2])i += 2answer.QLive = binary.BigEndian.Uint32(buf[i : i+4])i += 4answer.QLen = binary.BigEndian.Uint16(buf[i : i+2])i += 2

後面的CName是關鍵,解析也要按照類型進行。一種類型是CNAME類型,也就是別名,我的網域名稱www.cyeam.com的別名就是vm68h.x.incapdns.net,這是我的CDN。還有一種就是真實IP,返回別名也沒多大用,IP才能解決問題,所以Answer裡面的第二個就是返回這個別名的真實IP149.126.77.152。所以一個按字串處理,一個按數文書處理。Answer裡面的分類說明瞭解析類型,如果值是1,說明是A記錄,也就是IP,如果值是5,是CNAME記錄。解析Answer代碼如下:

if answer.Qtype == dnsTypeCNAME {domain_count := int(buf[i])i++for buf[i] != 0 {if domain_count > 0 {answer.CName += string(buf[i:i+domain_count]) + "."i += domain_countdomain_count = 0} else {domain_count = int(buf[i])i++}}i++answer.CName = strings.TrimRight(answer.CName, ".")} else if answer.Qtype == dnsTypeA {for m := 0; m < int(answer.QLen); m++ {answer.CName += fmt.Sprintf("%d.", buf[i+m])}answer.CName = strings.TrimRight(answer.CName, ".")}

Answer裡面還會包含結果的長度資訊,用這個來遍曆得到結果內容。

完整請求如下:

service := "223.5.5.5:53"udpAddr, err := net.ResolveUDPAddr("udp", service)checkError(err)conn, err := net.DialUDP("udp", nil, udpAddr)checkError(err)question := dnsQuestion{"www.cyeam.com", dnsTypeA, dnsClassINET}out := DnsMsg{}out.Id = 2015out.Bits |= _RDout.Questions = append(out.Questions, question)fmt.Println(out.Pack())_, err = conn.Write(out.Pack())checkError(err)buf := []byte{}buf = make([]byte, 512)n, err := conn.Read(buf[0:])checkError(err)fmt.Println(buf[0:n])fmt.Println(out.Unpack(buf[0:n]))os.Exit(0)

解析完成後的結構體列印結果如下:

&{2015 33152 1 2 0 0 [{www.cyeam.com 1 1}] [{49164 5 1 30 22 vm68h.x.incapdns.net} {49195 1 1 30 4 149.126.77.152}]}

涉及到的的資料包,可以從這裡訪問到。完整代碼可以參考這裡。

參考文獻
  1. 《電腦網路(第五版)》謝希仁
  2. What does a DNS request look like? - serverfault

原文連結:DNS協議Golang實現,轉載請註明來源!

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.