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?

2
  • 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 Commented Dec 16, 2016 at 6:57
  • To state it another way, the client isn't connecting with IPv4, so there's no IPv4 address to get. Commented Dec 16, 2016 at 14:34

1 Answer 1

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

    }
Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.