I want to integrate ReCAPTCHA to my GAE Golang web application. In order to verify a captcha, I need to get user's IP address. How can I fetch user's IP address from a form post?
The answers above neglect to check if user's IP is forwarded by a proxy. In a lot of cases, the IP that you will find in the RemoteAddr is the IP of a proxy that is forwarding the user's request to you - not the user's IP address!
A more accurate solution would look like this:
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
}
Use net.SplitHostPort:
ip, _, _ := net.SplitHostPort(r.RemoteAddr)
inside your handler function call r.RemoteAddr to receive ip:port
like this:
func renderIndexPage(w http.ResponseWriter, r *http.Request) {
ip := strings.Split(r.RemoteAddr,":")[0]
}
update 02/15/2017 as @Aigars Matulis pointed out, in current version there is already a function todo this
ip, _, _ := net.SplitHostPort(r.RemoteAddr)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With