go-ddns-svc/module/tools/tools.go

31 lines
561 B
Go
Raw Normal View History

2019-05-03 09:17:44 +00:00
package tools
import (
"net"
"net/http"
"net/textproto"
"strings"
)
// RemoteIP -
func RemoteIP(req *http.Request) string {
ips := make([]string, 0)
if headerAddr := req.Header.Get(textproto.CanonicalMIMEHeaderKey("X-Forwarded-For")); len(headerAddr) > 0 {
ips = strings.Split(headerAddr, ",")
}
if len(ips) > 0 && len(ips[0]) > 0 {
rip, _, err := net.SplitHostPort(ips[0])
if err != nil {
return ips[0]
}
return rip
}
ip := req.RemoteAddr
if rip, _, err := net.SplitHostPort(ip); err == nil {
return rip
} else {
return ip
}
}