gpt4 book ai didi

golang 强制 net/http 客户端使用 IPv4/IPv6

转载 作者:IT王子 更新时间:2023-10-29 02:08:30 28 4
gpt4 key购买 nike

我正在使用 go1.11 net/http 并想检测域是否仅支持 ipv6。

你做了什么?

我创建了自己的 DialContext,因为我想检测域是否仅支持 ipv6。下面的代码

package main
import (
"errors"
"fmt"
"net"
"net/http"
"syscall"
"time"
)
func ModifiedTransport() {
var MyTransport = &http.Transport{
DialContext: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
DualStack: false,
Control: func(network, address string, c syscall.RawConn) error {
if network == "ipv4" {
// I want to cancel connection here client.Get("http://myexample.com") return a non-nil err.
return errors.New("you should not use ipv4")
}
return nil
},
}).DialContext,
MaxIdleConns: 100,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
}
var myClient = http.Client{Transport: MyTransport}
resp, myerr := myClient.Get("http://www.github.com")
if myerr != nil {
fmt.Println("request error")
return
}
var buffer = make([]byte, 1000)
resp.Body.Read(buffer)
fmt.Println(string(buffer))
}
func main(){
ModifiedTransport();
}

我现在不知道如何关闭请求,即使我可以进入 network == "ipv4"

加法

Python 可以通过 Force requests to use IPv4 / IPv6 解决问题.我不知道如何在 golang 中做到这一点。有人可以帮助我吗?非常感谢!

最佳答案

传递给 Control 函数的 network 是用于 IPv4 连接的 tcp4 或用于 IPv6 的 tcp6连接,如果您正在建立传出 TCP 连接。

来自 type Dialer 的评论:

        // Network and address parameters passed to Control method are not
// necessarily the ones passed to Dial. For example, passing "tcp" to Dial
// will cause the Control function to be called with "tcp4" or "tcp6".

(在非 TCP 连接的情况下,other strings 是可能的。)

Known networks are "tcp", "tcp4" (IPv4-only), "tcp6" (IPv6-only), "udp", "udp4" (IPv4-only), "udp6" (IPv6-only), "ip", "ip4" (IPv4-only), "ip6" (IPv6-only), "unix", "unixgram" and "unixpacket".

关于golang 强制 net/http 客户端使用 IPv4/IPv6,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53055808/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com