使用gin-gonic
时,我试图获取客户端的IP地址,但是有时它会给我我不需要的IPv6地址。
我当前的代码如下:
web.POST("/path", func(c *gin.Context) {
ipAddr := c.ClientIP() // sometimes ipv4, sometimes ipv6
如何仅获取IPv4地址?
作为参考,我仅在侦听IPv4地址:
server := &http.Server{
Handler: router,
}
l, err := net.Listen("tcp4", cfg.Listen)
if err != nil {
panic(err)
}
err = server.Serve(l)
以下是我收到的IPv6地址的示例:
2402:800:6371:2f72:xxxx:bf67:3689:95df
2001:44b8:2169:c800:xxxx:c80a:b134:cc40
答案 0 :(得分:0)
不确定这是否有帮助,但下面的这个功能帮助我获得了 IP 地址
func getClientIPByHeaders(req *http.Request) (ip string, err error) {
// Client could be behid a Proxy, so Try Request Headers (X-Forwarder)
ipSlice := []string{}
ipSlice = append(ipSlice, req.Header.Get("X-Forwarded-For"))
ipSlice = append(ipSlice, req.Header.Get("x-forwarded-for"))
ipSlice = append(ipSlice, req.Header.Get("X-FORWARDED-FOR"))
for _, v := range ipSlice {
log.Printf("debug: client request header check gives ip: %v", v)
if v != "" {
return v, nil
}
}
err = errors.New("error: Could not find clients IP address from the Request Headers")
return "", err
}