【问题标题】:Any way to tell DNS resolver in go to lookup IPV4 address only?有什么方法可以告诉 DNS 解析器仅查找 IPV4 地址?
【发布时间】:2020-11-22 17:58:33
【问题描述】:

我正在尝试将 Go 程序(即 Prometheus)配置为仅查找 IPv4 地址,但该程序用于 DNS 解析的 LookupIP 函数似乎没有此选项。

有什么办法可以解决它,还是我做错了什么? LookupIP 函数如src

// LookupIP looks up a host using the local resolver.
// It returns a slice of that host's IPv4 and IPv6 addresses.
func LookupIP(host string) ([]IP, error) {
    addrs, err := DefaultResolver.LookupIPAddr(context.Background(), host)
    if err != nil {
        return nil, err
    }
    ips := make([]IP, len(addrs))
    for i, ia := range addrs {
        ips[i] = ia.IP
    }
    return ips, nil
}

【问题讨论】:

  • 我们的环境中还没有部署 IPv6。所以任何 IPv6 查找都只会返回 NXDOMAIN。该程序可以正确获取 IPv4 地址,但我只是不希望它发送 IPv6 查询。 @DanielFarrell

标签: go


【解决方案1】:

我认为您正在寻找 LookupIP。这是相同的功能,但您通过了您所针对的 ip 网络。

// LookupIP looks up host for the given network using the local resolver.
// It returns a slice of that host's IP addresses of the type specified by
// network.
// network must be one of "ip", "ip4" or "ip6".
func (r *Resolver) LookupIP(ctx context.Context, network, host string) ([]IP, error) {

用法:


    net.DefaultResolver.LookupIP(context.Background(), "ip4", "host")

【讨论】:

  • 是的,我在问题中提到的同一个源文件中看到了该函数,但不知道如何调用它。该函数在 Prometheus 的源文件中调用如下,但不知道如何确保它调用此函数而不是具有相同名称但没有指定网络类型选项的函数。 go ips, err := net.LookupIP(hostname) if err != nil { // Return the system hostname if we can't look up the IP address. return hostname, nil }
  • 使用用法更新我的问题。
  • 太棒了!我会尝试用这个函数重新编译那个程序,看看它是如何工作的。谢谢!
猜你喜欢
  • 2016-04-08
  • 2012-12-25
  • 1970-01-01
  • 2022-10-24
  • 1970-01-01
  • 1970-01-01
  • 2020-06-10
  • 2015-02-19
  • 1970-01-01
相关资源
最近更新 更多