在Go中指定要查找的DNS服务器 [英] Specifying DNS server for lookup in Go

查看:312
本文介绍了在Go中指定要查找的DNS服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以指定用于名称查找的DNS服务器?

Is there a way to specify which DNS server to use for a name lookup?

查看 https://golang.org/pkg/net/#LookupHost 似乎只会使用本地解析器

Looking at https://golang.org/pkg/net/#LookupHost seems it will use only the local resolver

LookupHost looks up the given host using the local resolver. It returns a slice 
of that host's addresses.

也早于该链接

 It can use a pure Go resolver that sends DNS requests directly to 
 the servers listed in /etc/resolv.conf,

如何像使用dig一样对任意服务器进行查找?

How could one do a lookup against arbitrary servers like one can do with dig?

dig @8.8.8.8 google.com

推荐答案

/u/gac reddit

Answer from /u/g-a-c on reddit

如果我没看错(也许不是)...

If I'm reading that doc right (maybe not)...

使用您要使用的DNS地址,使用自定义拨号程序创建本地解析程序( https ://golang.org/pkg/net/#Resolver ),然后使用该Resolver的LookupAddr函数?

Create yourself a local Resolver, with a custom Dialer, using the DNS address you want to use (https://golang.org/pkg/net/#Resolver) then use the LookupAddr function of that Resolver?

package main

import (
    "context"
    "net"
    "time"
)

func main() {
    r := &net.Resolver{
        PreferGo: true,
        Dial: func(ctx context.Context, network, address string) (net.Conn, error) {
            d := net.Dialer{
                Timeout: time.Millisecond * time.Duration(10000),
            }
            return d.DialContext(ctx, "udp", "8.8.8.8:53")
        },
    }
    ip, _ := r.LookupHost(context.Background(), "www.google.com")

    print(ip[0])
}

这似乎可行-在我的防火墙上,这表明我的计算机正在打开与Google的连接,而不是本地域控制器

This seems to work - on my firewall this shows that my machine is opening connections to Google rather than a local domain controller

这篇关于在Go中指定要查找的DNS服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆