Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google App Engine Golang - how to get user's IP address?

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?

like image 763
ThePiachu Avatar asked Jun 20 '13 19:06

ThePiachu


3 Answers

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
}
like image 188
orcaman Avatar answered Sep 20 '22 07:09

orcaman


Use net.SplitHostPort:

ip, _, _ := net.SplitHostPort(r.RemoteAddr)
like image 49
Aigars Matulis Avatar answered Oct 22 '22 17:10

Aigars Matulis


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)
like image 26
fmt.Println.MKO Avatar answered Oct 22 '22 17:10

fmt.Println.MKO