This is a creation in Article, where the information may have evolved or changed.
First, the problem description
http.RequestThe method below RemoteAddr() can get the address and port number of the client, which is used in a recent project.
There has been no problem with the use of the process, but when the project came online it was discovered that no matter how the IP was obtained, the client address was 127.0.0.1 .
For this question has been baffled its solution, finally engaged in a long time only nginx to find the reason.
Because the online project uses Nginx to do the reverse proxy, so that each time the server gets the Nginx address, that is 127.0.0.1 .
Specific content on this issue can be viewed: HTTP protocol x-real-ip, x-forwarded-for and REMOTE_ADDR headers
Second, the solution
When there is no proxy for HTTP requests, there is no problem with this method, but in the case of proxies, it can only be obtained by other means.
If nginx so, you can add the following code to the agent's code block:
1 2 3 4 5 6 7
|
... Proxy_set_header X-real-ip $remote _addr; Proxy_set_header x-forwarded-for $proxy _add_x_forwarded_for; Proxy_pass http://192.168.234.131; ... }
|
The real address is set to X-Real-IP and two request headers before Nginx forwarding, and is X-Forwarded-For then retrieved from their values as needed.
func Getcurrentip (R http. Request) {
but note that the IP represented by these two request headers can be forged
if IP = = "" {
//when the request header does not exist and the proxy does not exist, obtain the IP
return IP
Span class= "line" >
1 2 3 4 5 6 7 8 9 10 | TD class= "Code" >