3

I have the following setup:

The request is made to the server using one of its IP addresses - let's say either 192.168.0.1(on eth0) or 192.168.0.2(on eth1). The server is listening on all addresses on the local machine (e.g. http.ListenAndServe(":8080", nil)).

How can I determine in the server code from the request which network interface (or IP address) it was sent to?

req.Host contains the host name for the server. Moreover, I can't see anything in the request headers.

2
  • 1
    I would edit the question as the fact your Go code is a proxy is irrelevant to the question. The question is basically "how do I know the local address of a TCP connection which is carrying out an HTTP request being processed?" Commented Jul 1, 2020 at 14:40
  • thanks @kostix, I rephrased the question better Commented Nov 4, 2020 at 21:49

1 Answer 1

3

ok, I figured out this for http library source code - incoming address is stored in request context under http.LocalAddrContextKey key. So to extract incomming IP address you need to do

r.Context().Value(http.LocalAddrContextKey)
Sign up to request clarification or add additional context in comments.

3 Comments

I'd look at the ConnContext callback of the http.Server: its second argument is a net.Conn of the client's connection, so one could probably call LocalAddr() on it and actually populate the context.
@Flimzy, no it works as expected: <play.golang.org/p/zTBqVQuZtFL> (I did a series of curl -s http://address_or_hostname:8080/ calls; this is a Debian box with two known IPv4 localhost addresses, one IPv6 localhost address and a C-class address on a private LAN).
(Verified that the OP's method works identically). So I'd mark the answer as accepted (this is OK on StackOverflow).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.