Howto get the client's IP Address in Revel?
In Beego:
func (this *baseController) getClientIp() string {
s := strings.Split(this.Ctx.Request.RemoteAddr, ":")
return s[0]
}
Foreword: I released this utility in my github.com/icza/gox
library, see httpx.ClientIP()
.
It's very similar in Revel too. The Controller
is a struct
which contains the http.Request
, so from there you have access to Request.RemoteAddr
, the one used in the above Beego example:
// ctrl is a struct embedding a pointer of github.com/revel/revel.Controller
s := strings.Split(ctrl.Request.RemoteAddr, ":")
ip := s[0]
Or in one line:
ip := strings.Split(ctrl.Request.RemoteAddr, ":")[0]
Note: There is no standard form for the value of the RemoteAddr
. It can be an IPv4 or an IPv6 address, it may or may not contain port, so the above algorithm (copied from the question) will not work in every case. The question was directed at how to obtain this RemoteAddr
and not how to parse it particularly. To easily parse address strings, use net.SplitHostPort()
, like:
host, port, err := net.SplitHostPort(ctrl.Request.RemoteAddr)
Note #2: If the request gets forwarded and/or goes through proxy servers, the RemoteAddr
field may not denote the original client that sent the request. Usually when a request is forwarded / goes through proxies, the original client is added in an HTTP header field called X-Forwarded-For
, which you can get like
ip := c.Request.Header.Get("X-Forwarded-For")