dspx15491 2018-02-26 00:59
浏览 24
已采纳

主机名-> IP TTL?

Does the go standard library expose the TTL for a hostname -> ip lookup?

For example: dig stackoverflow.com gives 291s:

stackoverflow.com.  291 IN  A   151.101.129.69
stackoverflow.com.  291 IN  A   151.101.193.69
stackoverflow.com.  291 IN  A   151.101.1.69
stackoverflow.com.  291 IN  A   151.101.65.69

I've looked through net but I can't find anything.

  • 写回答

1条回答 默认 最新

  • duanluan8390 2018-02-26 21:25
    关注

    Just in case, this is a basic example using miekg/dns library

    https://play.golang.org/p/65hFuth1s_2

    package main
    
    import (
        "flag"
        "fmt"
        "os"
    
        "github.com/miekg/dns"
    )
    
    func main() {
        domain := flag.String("domain", "stackoverflow.com", "domain name")
        flag.Parse()
        fmt.Printf("domain %s
    ", *domain)
    
        server := "8.8.4.4"
    
        c := dns.Client{}
        m := dns.Msg{}
        m.SetQuestion(*domain+".", dns.TypeA)
        r, _, err := c.Exchange(&m, server+":53")
        if err != nil {
            fmt.Fprintln(os.Stderr, err)
            os.Exit(1)
        }
        if len(r.Answer) == 0 {
            fmt.Fprintln(os.Stderr, "Could not found NS records")
            os.Exit(1)
        }
    
        for _, ans := range r.Answer {
            if a, ok := ans.(*dns.A); ok {
                fmt.Printf("%s. %d IN A %s
    ", *domain, ans.Header().Ttl, a.A.String())
            }
        }
    }
    

    The TTL is obtained by using ans.Header().Ttl.

    By default will use the domain stackoverflow.com, and output something like:

    domain stackoverflow.com
    stackoverflow.com. 32 IN A 151.101.1.69
    stackoverflow.com. 32 IN A 151.101.65.69
    stackoverflow.com. 32 IN A 151.101.129.69
    stackoverflow.com. 32 IN A 151.101.193.69
    

    You can pass any domain by using the domain flag:

    go run main.go -domain google.com
    

    It is also using Google public DNS server 8.8.4.4 for resolving.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效