简体   繁体   English

Golang gin 仅在 ipv4 中获取客户端 IP

[英]Golang gin get client IP in ipv4 only

I'm trying to get the IP address of the client when using gin-gonic but sometimes it gives me the IPv6 address which I don't want.我在使用gin-gonic时试图获取客户端的 IP 地址,但有时它会给我我不想要的 IPv6 地址。

My current code looks like this:我当前的代码如下所示:

web.POST("/path", func(c *gin.Context) {
    ipAddr := c.ClientIP() // sometimes ipv4, sometimes ipv6

How do I get only the IPv4 address?如何仅获取 IPv4 地址?

For reference I'm only listening on IPv4 address:作为参考,我只监听 IPv4 地址:

server := &http.Server{
    Handler: router,
}
l, err := net.Listen("tcp4", cfg.Listen)
if err != nil {
    panic(err)
}
err = server.Serve(l)

Here are examples of the IPv6 addresses I'm receiving:以下是我收到的 IPv6 地址示例:

2402:800:6371:2f72:xxxx:bf67:3689:95df
2001:44b8:2169:c800:xxxx:c80a:b134:cc40

Not sure if this helps, but this below function helped me to get the IPAddress不确定这是否有帮助,但是下面的这个功能帮助我获得了 IPAddress

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM