Reputation: 20095
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.
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?
For reference I'm only listening on IPv4 address:
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:
2402:800:6371:2f72:xxxx:bf67:3689:95df
2001:44b8:2169:c800:xxxx:c80a:b134:cc40
Upvotes: 3
Views: 12719
Reputation: 159
Not sure if this helps, but this below function helped me to get the 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
}
Upvotes: 2