Golang 内置库net 有一些函数能方便获取DNS 记录信息。

LookupIP

通过域名查询 IPv4 和 IPv6 信息

1
2
3
4
5
6
7
8
9
10
11
12
13
package main

import (
	"fmt"
	"net"
)

func main() {
	ipRecords, _ := net.LookupIP("google.com")
	for _, ip := range ipRecords {
		fmt.Println(ip)
	}
}

输出:

1
2
216.58.197.110
2404:6800:4005:804::200e

LookupCNAME

获取CNAME 信息

1
2
3
4
5
6
7
8
9
10
11
package main

import (
	"fmt"
	"net"
)

func main() {
	cname, _ := net.LookupCNAME("m.baidu.com")
	fmt.Println(cname)
}

输出:

1
wap.n.shifen.com.

LookupNS

Name Server (NS)

1
2
3
4
5
6
7
8
9
10
11
12
13
package main

import (
	"fmt"
	"net"
)

func main() {
	nameServer, _ := net.LookupNS("baidu.com")
	for _, ns := range nameServer {
		fmt.Println(ns)
	}
}

输出:

1
2
3
4
5
&{ns4.baidu.com.}
&{ns2.baidu.com.}
&{ns7.baidu.com.}
&{dns.baidu.com.}
&{ns3.baidu.com.}

MX records

1
2
3
4
5
6
7
8
9
10
11
12
13
package main

import (
	"fmt"
	"net"
)

func main() {
	mxRecords, _ := net.LookupMX("baidu.com")
	for _, mx := range mxRecords {
		fmt.Println(mx.Host, mx.Pref)
	}
}

输出:

1
2
3
4
5
mx.maillb.baidu.com. 10
mx.n.shifen.com. 15
mx50.baidu.com. 20
mx1.baidu.com. 20
jpmx.baidu.com. 20

SRV service record

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package main

import (
	"fmt"
	"net"
)

func main() {
	cname, srvs, err := net.LookupSRV("xmpp-server", "tcp", "baidu.com")
	if err != nil {
		panic(err)
	}

	fmt.Printf("\ncname: %s \n\n", cname)

	for _, srv := range srvs {
		fmt.Printf("%v:%v:%d:%d\n", srv.Target, srv.Port, srv.Priority, srv.Weight)
	}
}

输出:

1
2
3
cname: _xmpp-server._tcp.baidu.com. 

xmpp.wshifen.com.:5269:0:0

TXT records

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package main

import (
	"fmt"
	"net"
)

func main() {
	txtRecords, _ := net.LookupTXT("baidu.com")

	for _, txt := range txtRecords {
		fmt.Println(txt)
	}
}

输出:

1
2
google-site-verification=GHb98-6msqyx_qqjGl5eRatD3QTHyVB6-xQ3gJB5UwM
v=spf1 include:spf1.baidu.com include:spf2.baidu.com include:spf3.baidu.com a mx ptr -all

利用第三方工具

上面是使用标准库net 得到 DNS 信息,如果想要得到更多数据或更方便,可以使用第三方工具,如 https://github.com/miekg/dns

本文网址: https://golangnote.com/topic/245.html 转摘请注明来源