|
@@ -1,6 +1,7 @@
|
|
|
package geodb
|
|
|
|
|
|
import (
|
|
|
+ "log"
|
|
|
"net"
|
|
|
"net/http"
|
|
|
"strings"
|
|
@@ -8,14 +9,56 @@ import (
|
|
|
|
|
|
// Utilities function
|
|
|
func GetRequesterIP(r *http.Request) string {
|
|
|
- ip := r.Header.Get("X-Forwarded-For")
|
|
|
+ ip := r.Header.Get("X-Real-Ip")
|
|
|
if ip == "" {
|
|
|
- ip = r.Header.Get("X-Real-IP")
|
|
|
- if ip == "" {
|
|
|
- ip = strings.Split(r.RemoteAddr, ":")[0]
|
|
|
+ ip = r.Header.Get("X-Forwarded-For")
|
|
|
+ }
|
|
|
+ if ip == "" {
|
|
|
+ ip = r.RemoteAddr
|
|
|
+ }
|
|
|
+
|
|
|
+ /*
|
|
|
+ Possible shits that might be extracted by this code
|
|
|
+ 127.0.0.1:61001
|
|
|
+ [15c4:cbb4:cc98:4291:ffc1:3a46:06a1:51a7]:61002
|
|
|
+ 127.0.0.1
|
|
|
+ 158.250.160.114,109.21.249.211
|
|
|
+ [15c4:cbb4:cc98:4291:ffc1:3a46:06a1:51a7],109.21.249.211
|
|
|
+
|
|
|
+ We need to extract just the first ip address
|
|
|
+ */
|
|
|
+ requesterRawIp := ip
|
|
|
+ if strings.Contains(requesterRawIp, ",") {
|
|
|
+ //Trim off all the forwarder IPs
|
|
|
+ requesterRawIp = strings.Split(requesterRawIp, ",")[0]
|
|
|
+ }
|
|
|
+
|
|
|
+ //Trim away the port number
|
|
|
+ if strings.Contains(requesterRawIp, "]:") {
|
|
|
+ //e.g. [15c4:cbb4:cc98:4291:ffc1:3a46:06a1:51a7]:61002
|
|
|
+ requesterRawIp = strings.Split(requesterRawIp, "]:")[0]
|
|
|
+ requesterRawIp = strings.TrimSpace(requesterRawIp[1:])
|
|
|
+ //The remaining part should be a ipv6 string
|
|
|
+ //e.g. 15c4:cbb4:cc98:4291:ffc1:3a46:06a1:51a7
|
|
|
+ if !IsIPv6(requesterRawIp) {
|
|
|
+ //WTF is this?
|
|
|
+ log.Println("Unknown request IPv6 extracted: " + requesterRawIp)
|
|
|
+ return ""
|
|
|
}
|
|
|
+ } else if strings.Contains(requesterRawIp, ":") && strings.Contains(requesterRawIp, ".") {
|
|
|
+ //e.g. 127.0.0.1:61001
|
|
|
+ requesterRawIp = strings.Split(requesterRawIp, ":")[0]
|
|
|
+ requesterRawIp = strings.TrimSpace(requesterRawIp)
|
|
|
+ if !IsIPv4(requesterRawIp) {
|
|
|
+ log.Println("Unknown request IPv4 extracted: " + requesterRawIp)
|
|
|
+ return ""
|
|
|
+ }
|
|
|
+ } else if strings.HasPrefix(requesterRawIp, "[") && strings.HasSuffix(requesterRawIp, "]") {
|
|
|
+ //e.g. [15c4:cbb4:cc98:4291:ffc1:3a46:06a1:51a7]
|
|
|
+ requesterRawIp = requesterRawIp[1 : len(requesterRawIp)-1]
|
|
|
}
|
|
|
- return ip
|
|
|
+
|
|
|
+ return requesterRawIp
|
|
|
}
|
|
|
|
|
|
// Match the IP address with a wildcard string
|
|
@@ -75,3 +118,13 @@ func IsIPv6(ipStr string) bool {
|
|
|
|
|
|
return ip.To4() == nil && ip.To16() != nil
|
|
|
}
|
|
|
+
|
|
|
+// Check if an Ip string is ipv6
|
|
|
+func IsIPv4(ipStr string) bool {
|
|
|
+ ip := net.ParseIP(ipStr)
|
|
|
+ if ip == nil {
|
|
|
+ return false
|
|
|
+ }
|
|
|
+
|
|
|
+ return ip.To4() != nil
|
|
|
+}
|