」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 當存在多個網路卡時,如何限制 Go 的 HTTP 用戶端的 IP 位址?

當存在多個網路卡時,如何限制 Go 的 HTTP 用戶端的 IP 位址?

發佈於2024-11-08
瀏覽:970

How do I constrain the IP address of Go\'s HTTP client when multiple NICs are present?

如何限制HTTP 用戶端的IP 位址

Go 的http.Client 可以實現高效率的HTTP 要求,但是如果你的系統包含多個個NIC?

自訂 IP 綁定

要將 http.Client 綁定到特定 IP,請使用 net.Transport 實例修改其 Transport 欄位。這允許您指定net.Dialer來控制連接的本機位址。

程式碼範例

下面的程式碼片段示範如何將用戶端綁定到指定的本機IP位址:

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

func main() {
    // Resolve the local IP address
    localAddr, err := net.ResolveIPAddr("ip", "")
    if err != nil {
        panic(err)
    }

    // Create a TCPAddr instance to specify the local address without specifying a port
    localTCPAddr := net.TCPAddr{
        IP: localAddr.IP,
    }

    // Create an HTTP client with a custom transport that specifies the local address
    webclient := &http.Client{
        Transport: &http.Transport{
            Proxy:                 http.ProxyFromEnvironment,
            DialContext:          (&net.Dialer{
                LocalAddr:      &localTCPAddr,
                Timeout:       30 * time.Second,
                KeepAlive:     30 * time.Second,
                DualStack:     true,
            }).DialContext,
            MaxIdleConns:          100,
            IdleConnTimeout:       90 * time.Second,
            TLSHandshakeTimeout:   10 * time.Second,
            ExpectContinueTimeout: 1 * time.Second,
        },
    }

    // Execute an HTTP request using the customized client
    req, _ := http.NewRequest("GET", "http://www.google.com", nil)
    resp, _ := webclient.Do(req)
    defer resp.Body.Close()
    
    // Optionally, use httputil to get the status code and response body
    code, _ := httputil.DumpResponse(resp, true)
    fmt.Println(code)
}

透過使用此方法,您可以指定 HTTP 用戶端連線所使用的 IP 位址。這使您可以控制傳出 IP 以實現網路靈活性。

最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3