英文:
Is golang caching DNS?
问题
我正在运行一段 Golang 代码来解析一个 URL。
这个 URL 应该在 50% 的请求中返回一个 IP,而在另外 50% 的请求中返回另一个 IP。
当我执行 host
命令时,这个功能是正常工作的,但是当我使用 Go 解析 DNS 时却不行。在我的研究中,我看到的每个答案都说 Golang 不会缓存 DNS,但实际行为似乎不同。
有人能解释一下吗?
这是我的代码,我使用一个循环运行它 100 次:
for value in {1..100};do go run main.go;done
"fmt"
"net"
)
func main() {
iprecords, _ := net.LookupIP("google.com")
for _, ip := range iprecords {
fmt.Println(ip)
}
}
英文:
I'm running a piece of golang code to resolve a url.
This url should returns one ip on 50% of the requests and another ip on the others 50%.
This is working when I perform the host
command but not when I resolve the DNS using Go. On my research, every answer I saw they said Golang doesn't cache DNS but the behavior seems to be different.
Can anyone clarify that?
Here is my code and I'm using a for loop to run it 100 times:
for value in {1..100};do go run main.go;done
"fmt"
"net"
)
func main() {
iprecords, _ := net.LookupIP("google.com")
for _, ip := range iprecords {
fmt.Println(ip)
}
}
</details>
# 答案1
**得分**: 1
当在`OS X`上使用`CGO_ENABLED=1`(`go build`的默认设置)时,根据[net包文档](https://pkg.go.dev/net#hdr-Name_Resolution),`Go`将使用基于cgo的解析器:
> ...在不允许程序直接进行DNS请求的系统上(OS X)...
因此,如果你在`MacOS`上观察到DNS缓存,那么这是在操作系统级别上发生的。
你可以尝试使用`Go`的本机DNS解析器,看看是否可行。
你可以通过以下两种方式之一来实现:
CGO_ENABLED=0 go build # 禁用CGO
或者更加隐蔽地使用运行时环境变量:
export GODEBUG=netdns=go # 强制使用纯Go解析器
这种方法有其局限性,例如在VPN分流DNS路由中,使用`Go`的本机解析器将无法工作。具体情况可能有所不同。
<details>
<summary>英文:</summary>
When using CGO_ENABLED=1 (the `go build` default) on `OS X`, according to the [net package docs](https://pkg.go.dev/net#hdr-Name_Resolution), `Go` will use:
> ... the cgo-based resolver ... on systems that do not
> let programs make direct DNS requests (OS X)
so if you are observing DNS caching on `MacOS` - then this is happening at OS-level.
You can try using the `Go`'s native DNS resolver to see if that is a viable alternative.
You co this this by either:
CGO_ENABLED=0 go build # disabling CGO
or more subtly using the runtime env var:
export GODEBUG=netdns=go # force pure Go resolver
This has its limitations, for example on VPN split-tunnel DNS routing will not work using `Go`'s native resolver. YMMV.
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论