13

我想将 ReCAPTCHA 集成到我的 GAE Golang Web 应用程序中。为了验证验证码,我需要获取用户的 IP 地址。如何从表单帖子中获取用户的 IP 地址?

4

4 回答 4

49

使用net.SplitHostPort

ip, _, _ := net.SplitHostPort(r.RemoteAddr)
于 2014-02-06T22:20:56.360 回答
26

在您的处理程序函数中调用 r.RemoteAddr 以接收 ip:port

像这样:

func renderIndexPage(w http.ResponseWriter, r *http.Request) {
  ip := strings.Split(r.RemoteAddr,":")[0] 

}

正如@Aigars Matulis指出的那样,更新02/15/2017 ,在当前版本中已经有一个功能可以做到这一点

ip, _, _ := net.SplitHostPort(r.RemoteAddr)
于 2013-06-20T19:31:25.750 回答
26

上面的答案忽略了检查用户的 IP 是否由代理转发。在很多情况下,您将在 RemoteAddr 中找到的 IP 是向您转发用户请求的代理的 IP,而不是用户的 IP 地址!

更准确的解决方案如下所示:

package main

import (
    "net"
    "net/http"
)

func GetIP(r *http.Request) string {
    if ipProxy := r.Header.Get("X-FORWARDED-FOR"); len(ipProxy) > 0 {
        return ipProxy
    }
    ip, _, _ := net.SplitHostPort(r.RemoteAddr)
    return ip
}
于 2014-10-06T19:48:36.500 回答
0

This worked for me. I run go in 8081 and made a request from port 8080.

fmt.Printf("r: %+v\n", r) // Print all fields that you get in request

Output:

r: &{Method:POST URL:/email Proto:HTTP/1.1 ProtoMajor:1 ProtoMinor:1 Header:map[User-Agent:[Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/602.2.11 (KHTML, like Gecko) Version/10.0.1 Safari/602.2.11] Accept-Language:[en-us] Accept-Encoding:[gzip, deflate] Connection:[keep-alive] Accept:[/] Referer:[http://127.0.0.1:8080/] Content-Length:[9] Content-Type:[application/x-www-form-urlencoded; charset=UTF-8] Origin:[http://127.0.0.1:8080]] Body:0xc420012800 ContentLength:9 TransferEncoding:[] Close:false Host:127.0.0.1:8081 Form:map[] PostForm:map[] MultipartForm: Trailer:map[] RemoteAddr:127.0.0.1:62232 RequestURI:/email TLS: Cancel: Response: ctx:0xc420017860}

The Referer and Origin have my client IP.

ip := r.Referer() // Get Referer value
fmt.Println(ip) // print ip

Output:

http://127.0.0.1:8080/

于 2016-10-02T04:21:10.810 回答