golang强制net/http客户端使用IPv4/IPv6 [英] golang force net/http client to use IPv4 / IPv6

查看:432
本文介绍了golang强制net/http客户端使用IPv4/IPv6的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用go1.11 net/http,想确定某个域是否仅为ipv6.

I' using go1.11 net/http and want to decect if a domain is ipv6-only.

我创建自己的DialContext是因为我想检测域是否仅为ipv6.下面的代码

I create my own DialContext because want I to detect if a domain is ipv6-only. code below

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" ,我现在也不关闭请求.

I do not now how to close the request even when I can get into network == "ipv4".

Python可以通过强制使用IPv4/IPv6的请求来解决问题.我不知道如何在golang中做到这一点.有人可以帮我吗?非常感谢!

Python can solve the question via Force requests to use IPv4 / IPv6. I do not know how to do it in golang. Could someone one help me? Thanks so much!

推荐答案

哦.我自己解决了这个问题.

Oh. I fixed the problem myself.

我们无法配置强制ipv6连接,因为它是硬编码的

We could not configure force ipv6 connection because it is hard coded

...
if cm.scheme() == "https" && t.DialTLS != nil {
        var err error
        pconn.conn, err = t.DialTLS("tcp", cm.addr())
        if err != nil {
            return nil, wrapErr(err)
        }
...

(在此处编码)

我为transport.go添加了一个ipv6only标志,一个getTcpString()即可.

I add a ipv6only flag for transport.go, a getTcpString() and it works.

(在此处差异)

这篇关于golang强制net/http客户端使用IPv4/IPv6的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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