fix real ip

This commit is contained in:
fancl 2023-08-15 17:42:32 +08:00
parent 4199b81b5f
commit d24f7efb0b
2 changed files with 39 additions and 2 deletions

View File

@ -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
}

View File

@ -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)
}