Created
May 21, 2018 12:02
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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