Golang Considerations for using REMOTEADDR () to obtain remote host addresses

Source: Internet
Author: User
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" >
TD class= "Code" >
 1  
2
3
4
5
6
7
8
9
10

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.