How to Constrain HTTP Client's IP Address
Go's http.Client enables efficient HTTP requests, but how do you restrict its IP address if your system houses multiple NICs?
Customizing IP Binding
To bind the http.Client to a specific IP, modify its Transport field with an instance of net.Transport. This allows you to designate the net.Dialer to control the local address for connections.
Code Example
The code snippet below demonstrates how to bind the client to a specified local IP address:
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)
}
By using this approach, you can specify the IP address used by the HTTP client's connections. This allows you to control the outgoing IP for networking flexibility.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3