去 http 强制使用 ipv4

问题描述 投票:0回答:1

我只是想让 golang http get 请求使用 ipv4

来自 golang Force net/http client to use IPv4 / IPv6 的答案对我不起作用。此外,我找到了以下答案,但这对我来说也不起作用:

package main

import (
    "fmt"
    "net"
    "net/http"
    "time"
)

func main() {
    // Create a transport object
    transport := &http.Transport{
        Dial: (&net.Dialer{
            Timeout:   30 * time.Second,
            KeepAlive: 30 * time.Second,
            DualStack: false, // This ensures only IPv4 is used
        }).Dial,
    }

    // Create an HTTP client with the custom transport
    client := &http.Client{
        Transport: transport,
    }

    // Create an HTTP GET request
    req, err := http.NewRequest("GET", "https://ifconfig.me/", nil)
    if err != nil {
        fmt.Println("Error creating request:", err)
        return
    }

    // Send the request using the client
    resp, err := client.Do(req)
    if err != nil {
        fmt.Println("Error sending request:", err)
        return
    }
    defer resp.Body.Close()

    // Handle the response as needed
    // ...
}

我仍然收到 IPv6 返回(来自 https://ifconfig.me/)。

请问有什么帮助吗?

go http get httpclient ipv4
1个回答
0
投票

你可以尝试像这样自定义拨号过程吗?

...
func main() {
    // Custom dialer that enforces IPv4
    dialer := &net.Dialer{
        Timeout:   30 * time.Second,
        KeepAlive: 30 * time.Second,
    }

    transport := &http.Transport{
        Dial: func(network, address string) (net.Conn, error) {
            // Resolve the address
            ipAddr, err := net.ResolveIPAddr("ip4", address)
            if err != nil {
                return nil, err
            }
            // Connect using only the IPv4 address
            return dialer.Dial("tcp4", ipAddr.String())
        },
    }

    // Create an HTTP client with the custom transport
    client := &http.Client{
        Transport: transport,
    }

    // Create an HTTP GET request
    req, err := http.NewRequest("GET", "https://ifconfig.me/", nil)
    if err != nil {
        fmt.Println("Error creating request:", err)
        return
    }

    // Send the request using the client
    resp, err := client.Do(req)
    if err != nil {
        fmt.Println("Error sending request:", err)
        return
    }
    defer resp.Body.Close()

    // Handle the response as needed
    // ...
}

© www.soinside.com 2019 - 2024. All rights reserved.