(原) DNS服务速度测试工具

原创文章,请后转载,并注明出处。

名字:DNSWho (这英语,嘎嘎的)

功能:测试各个DNS服务器返回时间,按速度进行排序显示。你可以根据排序来设置自己的DNS服务器,肯定有大大的(人应该感受不到)的速度改善。

使用:go run main.go [scwy.net]

说明:简单工具,能用就行,高手自行优化。什么并发,排序之类。

package main

import (
	"fmt"
	"os"
	"strings"
	"time"

	"github.com/miekg/dns"
)

func main() {
	domain := "www.baidu.com."
	dnsServer := []string{
		"223.5.5.5",
		"218.203.244.62",
		"119.29.29.29",
		"180.76.76.76",
		"1.0.0.1",
		"1.1.1.1",
		"114.114.114.144",
		"114.114.114.119",
		"114.114.114.110",
		"210.2.4.8",
		"208.67.222.222",
		"84.200.69.80",
		"9.9.9.9",
		"1.2.4.8",
		"123.125.81.6",
		"61.139.2.69",
	}
	ds := make(map[string]int64)

	if len(os.Args) == 2 {
		domain = os.Args[1]
	}
	if strings.HasSuffix(domain, ".") == false {
		domain = domain + "."
	}

	fmt.Printf("域名查询 %s--------------------------\n", domain)

	c := dns.Client{
		Timeout: 5 * time.Second,
	}

	m := dns.Msg{}
	m.SetQuestion(domain, dns.TypeA)

	for _, i := range dnsServer {
		_, tts, err := c.Exchange(&m, i+":53")
		if err != nil {
			//fmt.Println("dns error")
			continue
		} else {
			ds[i] = tts.Nanoseconds()
			fmt.Printf("%20s  耗时 %10s\n", i, tts)
		}
	}

	var sort []int64
	for _, i := range ds {
		sort = append(sort, i)
	}

	bubbleSort(sort)
	fmt.Println("DNS时间排序结果 -------------------------------")
	for _, n := range sort {
		for m, o := range ds {
			if n == o {
				fmt.Printf("%20s  耗时 %12fms\n", m, (float64(o) / 1e6))
				break
			}
		}
	}
}

// 冒泡排序
func bubbleSort(arr []int64) {
	var flag bool
	for i := 0; i < len(arr)-1; i++ {
		flag = true
		for j := 0; j < len(arr)-i-1; j++ {
			if arr[j] > arr[j+1] {
				flag = false
				arr[j], arr[j+1] = arr[j+1], arr[j]
			}
		}
		if flag {
			break
		}
	}
}

相关文章