2023-06-19 09:44:34 +00:00
|
|
|
package ip
|
2023-06-30 09:20:11 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"net"
|
|
|
|
"net/http"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
|
|
|
// 获取客户端ip地址
|
|
|
|
func GetClientIP(r *http.Request) (ip string, err error) {
|
|
|
|
xForwardedFor := r.Header.Get("X-Forwarded-For")
|
|
|
|
ip = strings.TrimSpace(strings.Split(xForwardedFor, ",")[0])
|
|
|
|
if ip != "" {
|
|
|
|
return ip, nil
|
|
|
|
}
|
|
|
|
ip = strings.TrimSpace(r.Header.Get("X-Real-Ip"))
|
|
|
|
if ip != "" {
|
|
|
|
return ip, nil
|
|
|
|
}
|
|
|
|
ip, _, err = net.SplitHostPort(strings.TrimSpace(r.RemoteAddr))
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
return ip, nil
|
|
|
|
}
|