lf215
lf215

Reputation: 959

Hostname -> 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.

Upvotes: 1

Views: 1177

Answers (1)

nbari
nbari

Reputation: 26925

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\n", *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\n", *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.

Upvotes: 2

Related Questions