Skip to content

Instantly share code, notes, and snippets.

@osmanmakal
Created May 21, 2018 12:02
Show Gist options
  • Select an option

  • Save osmanmakal/48a6d455dc0c7e26c393ec20f48233c9 to your computer and use it in GitHub Desktop.

Select an option

Save osmanmakal/48a6d455dc0c7e26c393ec20f48233c9 to your computer and use it in GitHub Desktop.
Remote IP Address with Go (X-Real-Ip and X-Forwarded-For included)
package lib
import (
"net"
"net/http"
"strings"
)
func GetIPAddr(r *http.Request) string {
ipaddr, _, _ := net.SplitHostPort(r.RemoteAddr)
PrivateRanges := []string{"10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16"}
for i, _ := range PrivateRanges {
if _, subnet, _ := net.ParseCIDR(PrivateRanges[i]); subnet.Contains(net.ParseIP(ipaddr)) {
for _, h := range []string{"X-Forwarded-For", "X-Real-Ip"} {
for _, ip := range strings.Split(r.Header.Get(h), ",") {
RealIp := net.ParseIP(strings.Replace(ip, " ", "", -1))
if check := net.ParseIP(RealIp.String()); check != nil {
ipaddr = RealIp.String()
}
}
}
}
}
return ipaddr
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment