0

I am using go-gin as server and rendering an html using the code like the following

func dashboardHandler(c *gin.Context) {
    c.HTML(200, "dashboard", gin.H{
        "title": "Dashboard"
})

Along with title I want to pass the remote client's IPV4 address as well. I tried using the following code to get the IP address but for localhost it gives me ::1:56797 as output. My server is running on localhost:8080

ip, port, err := net.SplitHostPort(c.Request.RemoteAddr)
fmt.Println(ip + ":" + port)
if err != nil {
    fmt.Println(err.Error())
}

I followed Correct way of getting Client's IP Addresses from http.Request (Golang) for reference. Is there any way I get the IPV4 address from the request?

Community
  • 1
  • 1
codec
  • 7,978
  • 26
  • 71
  • 127
  • 2
    Actually the output is correct, you're running your server with ipv4 and ipv6 support. If you only want to run your server with ipv4, you can check [here](http://stackoverflow.com/questions/38592064/go-lang-go-gin-listen-on-tcp4-not-tcp6) – Motakjuq Dec 16 '16 at 06:57
  • To state it another way, the client isn't connecting with IPv4, so there's no IPv4 address to get. – JimB Dec 16 '16 at 14:34

1 Answers1

2

you can use this function to get the ip and user agent, but it will give a bracket character if you are trying from localhost but if you try from somewhere else it will work.

func GetIPAndUserAgent(r *http.Request) (ip string, user_agent string) {
        ip = r.Header.Get("X-Forwarded-For")
        if ip == "" {
            ip = strings.Split(r.RemoteAddr, ":")[0]
        }

        user_agent = r.UserAgent()
        return ip, user_agent

    }
Said Saifi
  • 1,995
  • 7
  • 26
  • 45
  • 2
    `X-Forwarded-For` is the old header used by proxies to store a client's IP. It doesn't exist if there was no proxy, the proxy doesn't use the old header format, or the proxy simply doesn't include a Forwarded header at all. – JimB Dec 16 '16 at 14:29