GO获取客户端IP地址

hellsam · · 20127 次点击
<a href="/user/polaris" title="@polaris">@polaris</a> ~~~ 我直接输出的 fmt.Fprintln(w, RemoteIp) 怎么返回的是 0x72b650 而不是IP呢 ~~~
#7
更多评论
~~~ 哦看错了 fmt.Println(r.RemoteAddr) 是可以获取IP的 就是后面带个 端口 有点别扭 怎么去掉呢 ~~~
#1
polaris
社区,需要你我一同完善!
```go func RemoteIp(req *http.Request) string { remoteAddr := req.RemoteAddr if ip := req.Header.Get(XRealIP); ip != &#34;&#34; { remoteAddr = ip } else if ip = req.Header.Get(XForwardedFor); ip != &#34;&#34; { remoteAddr = ip } else { remoteAddr, _, _ = net.SplitHostPort(remoteAddr) } if remoteAddr == &#34;::1&#34; { remoteAddr = &#34;127.0.0.1&#34; } return remoteAddr } ```
#2