find IP address by domain in go

Viewed 3824

I am using below code for an API to find ip address for a given domain:

func IPFinder(c *gin.Context) {
    var domain models.Domain
    c.BindJSON(&domain)
    addr, err := net.LookupIP(domain.DomainName)
    if err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
    } else {
        c.JSON(http.StatusOK, gin.H{"ip_address": addr})
    }
    return
}

For the below request:

{
    "domain_name": "google.com"
}

getting response as :

{
    "ip_address": [
        "2404:6800:4002:80a::200e",
        "172.217.167.46"
    ]
}

Here this LookupIP method is giving the slice containing ipv4 and ipv6 address of that domain. Is there any other way of any other 3rd party lib in GoLang using which I can get output containing only the ip address like below :

{
    "ip_address": "172.217.167.46"
}
2 Answers

If you're only interested in IPv4 addresses, you can get it like this:

package main

import (
    "fmt"
    "net"
)

func main(){
    ips, _ := net.LookupIP("google.com")
    for _, ip := range ips {
        if ipv4 := ip.To4(); ipv4 != nil {
            fmt.Println("IPv4: ", ipv4)
        }
    }
}

You could use DNS-over-HTTPS service from cloudflare-dns.com, see here.

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
)

type DnsJson struct {
    Status   int  `json:"Status"`
    TC       bool `json:"TC"`
    RD       bool `json:"RD"`
    RA       bool `json:"RA"`
    AD       bool `json:"AD"`
    CD       bool `json:"CD"`
    Question []struct {
        Name string `json:"name"`
        Type int    `json:"type"`
    } `json:"Question"`
    Answer []struct {
        Name string `json:"name"`
        Type int    `json:"type"`
        TTL  int    `json:"TTL"`
        Data string `json:"data"`
    } `json:"Answer"`
}

func main() {

    req, err := http.NewRequest("GET", "https://cloudflare-dns.com/dns-query", nil)
    if err != nil {
        log.Fatal(err)
    }

    q := req.URL.Query()
    q.Add("ct", "application/dns-json")
    q.Add("name", "cloudflare.com") // Insert here your domain

    req.URL.RawQuery = q.Encode()

    client := &http.Client{}

    if err != nil {
        log.Fatal(err)
    }
    res, err := client.Do(req)
    defer res.Body.Close()
    body, err := ioutil.ReadAll(res.Body)

    var dnsResult DnsJson
    if err := json.Unmarshal(body, &dnsResult); err != nil {
        log.Fatal(err)
    }

    for _, dnsAnswer := range dnsResult.Answer {
        fmt.Println("IP:", dnsAnswer.Data)
    }

    // Output
    // IP: 104.17.175.85
    // IP: 104.17.176.85
}
Related