如何从请求对象中获取远程客户端的IPv4地址

huangapple go评论69阅读模式
英文:

How to get remote client's IPV4 address from request object

问题

我正在使用go-gin作为服务器,并使用以下代码渲染HTML页面:

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

除了标题之外,我还想传递远程客户端的IPv4地址。我尝试使用以下代码获取IP地址,但对于本地主机,它给我输出::1:56797。我的服务器正在localhost:8080上运行。

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

我参考了https://stackoverflow.com/questions/27234861/correct-way-of-getting-clients-ip-addresses-from-http-request-golang。有没有办法从请求中获取IPv4地址?

英文:

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 https://stackoverflow.com/questions/27234861/correct-way-of-getting-clients-ip-addresses-from-http-request-golang for reference. Is there any way I get the IPV4 address from the request?

答案1

得分: 2

你可以使用这个函数来获取IP地址和用户代理,但是如果你是从本地主机尝试,它会返回一个括号字符,但如果你从其他地方尝试,它会正常工作。

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
}
英文:

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
    
    }

huangapple
  • 本文由 发表于 2016年12月16日 12:52:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/41177475.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定