Browse Source

fix real ip

fancl 1 year ago
parent
commit
d24f7efb0b
2 changed files with 39 additions and 2 deletions
  1. 11 2
      entry/http/context.go
  2. 28 0
      entry/http/context_test.go

+ 11 - 2
entry/http/context.go

@@ -38,6 +38,7 @@ func (ctx *Context) reset(req *http.Request, res http.ResponseWriter, ps map[str
 
 func (ctx *Context) RealIp() string {
 	var (
+		s      string
 		pos    int
 		ipaddr string
 	)
@@ -48,8 +49,16 @@ func (ctx *Context) RealIp() string {
 	}
 	ipaddr, _, _ = net.SplitHostPort(ctx.Request().RemoteAddr)
 __end:
-	if pos = strings.LastIndexByte(ipaddr, ','); pos > -1 {
-		ipaddr = ipaddr[:pos]
+	for {
+		if pos = strings.IndexByte(ipaddr, ','); pos > -1 {
+			s = strings.TrimSpace(ipaddr[:pos])
+			if netip := net.ParseIP(s); netip != nil && !netip.IsPrivate() {
+				return s
+			}
+			ipaddr = ipaddr[pos+1:]
+		} else {
+			break
+		}
 	}
 	return ipaddr
 }

+ 28 - 0
entry/http/context_test.go

@@ -0,0 +1,28 @@
+package http
+
+import (
+	"net"
+	"strings"
+	"testing"
+)
+
+func TestContext_RealIp(t *testing.T) {
+	var (
+		pos int
+		s   string
+	)
+	ipaddr := "192.168.6.76, 192.168.6.76, 116.24.65.173,192.168.6.76"
+	for {
+		if pos = strings.IndexByte(ipaddr, ','); pos > -1 {
+			s = strings.TrimSpace(ipaddr[:pos])
+			if netip := net.ParseIP(s); netip != nil && !netip.IsPrivate() {
+				t.Log(s)
+				break
+			}
+			ipaddr = ipaddr[pos+1:]
+		} else {
+			break
+		}
+	}
+	t.Log(ipaddr)
+}