Home  >  Article  >  Backend Development  >  How to Enforce IPv4/IPv6 Usage in Go\'s net/http Client?

How to Enforce IPv4/IPv6 Usage in Go\'s net/http Client?

Linda Hamilton
Linda HamiltonOriginal
2024-11-01 04:33:28308browse

How to Enforce IPv4/IPv6 Usage in Go's net/http Client?

Enforcing IPv4/IPv6 Usage in Go's net/http Client

Issue:

Using Go 1.11's net/http client, how can one determine if a domain is IPv6-only and prevent it from using IPv4 if desired?

Solution:

To enforce IPv4 or IPv6 usage in Go's net/http client, modify its DialContext function using the Control option of the net.Dialer. This function checks the network type used for outgoing connections.

Copy the following code into your main function:

<code class="go">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" {
                    // Force cancellation of IPv4 connections
                    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))
}</code>

Explanation:

  • The Control function is called with the network type of the outgoing connection (e.g., "tcp4" or "tcp6").
  • If the network type is "ipv4," the Control function returns an error to prevent the establishment of an IPv4 connection.
  • By using this approach, only IPv6 connections will be allowed, effectively blocking any IPv4 usage.

The above is the detailed content of How to Enforce IPv4/IPv6 Usage in Go\'s net/http Client?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn