2

I a using go's http package to make http requests. When having several interfaces on Ubuntu Linux, how can I configure go's http client to use a specific interface or IP address to perform the request?

How does the default http client decide which interface it uses?

2
  • note that in linux you don't normally bind to an interface, you choose the IP address to bind to and the interface is chosen during routing. Commented Jun 15, 2017 at 15:42
  • 1
    Wanted to say that on Linux you actually can bind to interface via SO_BINDTODEVICE. I already provided some details in my python response. And binding to IP is not always works as binding to interface (cause it still can route traffic through other interfaces). Here's golang example. Commented Aug 24, 2021 at 12:25

1 Answer 1

11

Go's http.Client makes requests using a http.RoundTripper. This, in turn, uses a net.Dialer to establish the outbound network connections. net.Dialer has a field LocalAddr which specifies the local address from which the connections will be made. You can use your own Client, with your own RoundTripper, with your own net.Dialer, specifying the LocalAddr you want to use. You can see how each of these is instantiated in the stdlib code linked from the documentation, and copy the mechanisms used to create the default instances to maintain default behavior while overriding the LocalAddr as needed.

Sign up to request clarification or add additional context in comments.

1 Comment

Hi, that's the response however, I personally always like to see an example, that may be obvious for some, not for others, or if you don't have an example in hand try pointing to some link that has, I am gonna do it now: gist.github.com/2minchul/191716b3ca8799f53362746731d08e91

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.