miekg / dns

DNS library in Go
https://miek.nl/2014/august/16/go-dns-package
BSD 3-Clause "New" or "Revised" License
7.99k stars 1.13k forks source link

Idiomatic way of printing the IPs / A records returned by a query #1546

Closed pantelis-karamolegkos closed 6 months ago

pantelis-karamolegkos commented 6 months ago

I just want to get / print the IPs / A records of a simple query.

Is there a more idiomatic way of going about it, rather than splitting the answer as per the example below

package main

import (
    "fmt"
    "log"
    "strings"

    "github.com/miekg/dns"
)

func main() {
    m1 := new(dns.Msg)
    m1.RecursionDesired = true
    m1.Question = make([]dns.Question, 1)
    m1.SetQuestion(dns.Fqdn("skroutz.gr"), dns.TypeA)
    c := new(dns.Client)
    in, rtt, err := c.Exchange(m1, "8.8.8.8:53")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Round Trip Time: %s\n", rtt)
    for i := range in.Answer {
        if t, ok := in.Answer[i].(*dns.A); ok {
            answerParts := strings.Split(t.String(), "\t")
            fmt.Println(answerParts[len(answerParts)-1])
        }
    }
}
rdrozhdzh commented 6 months ago

Probably

if t, ok := in.Answer[i].(*dns.A); ok {
  fmt.Println(t.A.String())
}
pantelis-karamolegkos commented 6 months ago

good suggestion; I see that it prints something in the likes of

185.6.76.42
185.6.76.42

Is there an inherent library way of getting this either as a []netIP or at least []string or do I have to resort to manual parsing?

pantelis-karamolegkos commented 6 months ago

(and I don't get why it fetches twice the same A record)

janik-cloudflare commented 6 months ago

Is there an inherent library way of getting this either as a []netIP or at least []string or do I have to resort to manual parsing?

The t.A from @rdrozhdzh' comment is a net.IP. To get it into an array, though, you'll have to write a loop yourself, since you're combining data from multiple records.

(and I don't get why it fetches twice the same A record)

It shouldn't and doesn't for me. Did you remove the fmt.Println you already had in your initial code above?