What's the correct way to get all client's IP Addresses from http.Request
? In PHP
there are a lot of variables that I should check. Is it the same on Go?
One that I found is:
req.RemoteAddr
And is the request case sensitive? for example x-forwarded-for
is the same as X-Forwarded-For
and X-FORWARDED-FOR
? (from req.Header.Get("X-FORWARDED-FOR")
)
Here a completely working example
This has nothing to do with Go (or PHP for that matter). It just depends on what the client, proxy, load-balancer, or server is sending. Get the one you need depending on your environment.
http.Request.RemoteAddr
contains the remote IP address. It may or may not be your actual client.No, why not try it yourself? http://play.golang.org/p/YMf_UBvDsH
Looking at http.Request you can find the following member variables:
You can use
RemoteAddr
to get the remote client's IP address and port (the format is "IP:port"), which is the address of the original requestor or the last proxy (for example a load balancer which lives in front of your server).This is all you have for sure.
Then you can investigate the headers, which are case-insensitive (per documentation above), meaning all of your examples will work and yield the same result:
This is because internally
http.Header.Get
will normalise the key for you. (If you want to access header map directly, and not throughGet
, you would need to use http.CanonicalHeaderKey first.)Finally,
"X-Forwarded-For"
is probably the field you want to take a look at in order to grab more information about client's IP. This greatly depends on the HTTP software used on the remote side though, as client can put anything in there if it wishes to. Also, note the expected format of this field is the comma+space separated list of IP addresses. You will need to parse it a little bit to get a single IP of your choice (probably the first one in the list), for example:will produce: