GO获取客户端IP地址

hellsam · · 20096 次点击
<a href="/user/polaris" title="@polaris">@polaris</a> 你这个编译报错 有些是自定义函数吧 ~~~ .\main.go:34:26: undefined: XRealIP .\main.go:36:32: undefined: XForwardedFor .\main.go:39:22: undefined: net ~~~
#3
更多评论
~~~ 哦看错了 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