dignslookup

1. net包的使用

和dns相关结构体方法

# nameserver结构体
type NS struct {
    Host string
}


# srv记录 指定该域名由哪个DNS服务器来进行解析
type SRV struct {
    Target   string
    Port     uint16
    Priority uint16
    Weight   uint16
}


# dns正向解析(域名解析到cname或者实际的ip地址)
## 仅返回指定域名name的cname地址
func LookupCNAME(name string) (cname string, err error)

## 直接返回域名解析到地址.
func LookupHost(host string) (addrs []string, err error)

## 直接返回域名解析到地址,[]IP结构体.可以对具体ip进行相关操作(是否回环地址,子网,网络号等)
# type IP []byte
func LookupIP(host string) (addrs []IP, err error)

## DNS反向解析(ip地址反向解析查找解析到的域名)
# 根据ip地址查找主机名地址(必须得是可以解析到的域名)[dig -x ipaddress]
func LookupAddr(addr string) (name []string, err error)

使用net包进行dns解析查询

$ cat dns-test.go
package main

import (
  "net"
  "fmt"
  "os"
)


func main() {
  dns := "xxbandy.github.io"

  // 解析cname
  cname,_ := net.LookupCNAME(dns)

  // 解析ip地址
  ns, err := net.LookupHost(dns)
  if err != nil {
    fmt.Fprintf(os.Stderr, "Err: %s", err.Error())
    return
  }

  // 反向解析(主机必须得能解析到地址)
  dnsname,_ := net.LookupAddr("127.0.0.1")
  fmt.Println("hostname:",dnsname)

  // 对域名解析进行控制判断
  // 有些域名通常会先使用cname解析到一个别名上,然后再解析到实际的ip地址上
  switch {
    case cname != "":
        fmt.Println("cname:",cname)
        if len(ns) != 0 {
            fmt.Println("vips:")
            for _, n := range ns {
                fmt.Fprintf(os.Stdout, "%s\n", n)
            }
         }
    case len(ns) != 0:
        for _, n := range ns {
            fmt.Fprintf(os.Stdout, "%s\n", n)
        }
    default:
        fmt.Println(cname,ns)

  }

}

# 输出了本地127.0.0.1的主机名
# xxbandy.github.io的cname域名和实际解析的ip地址
$ go run dns-test.go
hostname: [localhost]
cname: xxbandy.github.io.
vips:
185.199.110.153
185.199.111.153
185.199.109.153
185.199.108.153

2. 分析dns解析过程以及系统调用

注意:在linux环境下可以使用dig trace来追踪域名解析过程
目的ip
$ cat dns-test2.go
package main

import (
  "net"
  "fmt"
  "os"
)
func main() {
  dns := "xxbandy.github.io"
  ns, err := net.LookupHost(dns)
  if err != nil {
    fmt.Fprintf(os.Stderr, "Err: %s"