How do I bind an `http.Client` to a specific IP address in Go?

Linda Hamilton
Release: 2024-10-28 01:48:29
Original
901 people have browsed it

How do I bind an `http.Client` to a specific IP address in Go?

Binding an http.Client to a Specific IP Address in Go

When dealing with multiple network interfaces on a client machine, it becomes imperative to bind an http.Client to a specific NIC or SRC IP address to ensure precise network traffic routing. The following guide will walk you through the necessary steps to achieve this in Go.

To begin, it's crucial to set the http.Client.Transport field to an instance of net.Transport. This allows you to specify the net.Dialer you intend to use. Subsequently, net.Dialer empowers you to define the local address from which connections are initiated.

Consider the following code snippet:

<code class="go">localAddr, err := net.ResolveIPAddr("ip", "<my local address>")
if err != nil {
  panic(err)
}

localTCPAddr := net.TCPAddr{
    IP: localAddr.IP,
}

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,
    },
}</code>
Copy after login

By following these steps, you can effectively bind your http.Client to a specific IP address, ensuring control over the network traffic originating from your client machine.

The above is the detailed content of How do I bind an `http.Client` to a specific IP address in Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!