GO获取客户端IP地址

hellsam · · 20165 次点击
要优先使用XForwardedFor
#10
更多评论
~~~ 哦看错了 fmt.Println(r.RemoteAddr) 是可以获取IP的 就是后面带个 端口 有点别扭 怎么去掉呢 ~~~
#1
polaris
社区,需要你我一同完善!
```go func RemoteIp(req *http.Request) string { remoteAddr := req.RemoteAddr if ip := req.Header.Get(XRealIP); ip != "" { remoteAddr = ip } else if ip = req.Header.Get(XForwardedFor); ip != "" { remoteAddr = ip } else { remoteAddr, _, _ = net.SplitHostPort(remoteAddr) } if remoteAddr == "::1" { remoteAddr = "127.0.0.1" } return remoteAddr } ```
#2