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

fan*_*nxu 10 web-crawler go

我使用 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();
}
Run Code Online (Sandbox Code Playgroud)

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

添加

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

Mic*_*ton 3

如果您要建立传出 TCP 连接,则传递network给该Control函数的参数要么tcp4用于 IPv4 连接tcp6,要么用于 IPv6 连接。

来自评论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".
Run Code Online (Sandbox Code Playgroud)

(如果是非 TCP 连接,则可以使用其他字符串。)

已知网络有“tcp”、“tcp4”(仅限 IPv4)、“tcp6”(仅限 IPv6)、“udp”、“udp4”(仅限 IPv4)、“udp6”(仅限 IPv6)、“ip” 、“ip4”(仅限 IPv4)、“ip6”(仅限 IPv6)、“unix”、“unixgram”和“unixpacket”。