在go中按域查找IP地址

find IP address by domain in go

我正在使用下面的代码 API 来查找给定域的 IP 地址:

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
}

对于以下请求:

{
    "domain_name": "google.com"
}

收到回复:

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

这里这个 LookupIP 方法给出了包含该域的 ipv4 和 ipv6 地址的切片。 GoLang 中是否有任何其他第三方库的任何其他方式,我可以使用它获得仅包含 ip 地址的输出,如下所示:

{
    "ip_address": "172.217.167.46"
}

如果您只对 IPv4 地址感兴趣,可以这样获取:

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)
        }
    }
}

您可以使用 cloudflare-dns.com 的 DNS-over-HTTPS 服务,参见 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
}