tkcashgame_v4/pkg/utils/net.go

52 lines
956 B
Go

package utils
import (
"net"
"net/http"
"strings"
)
// GetLocalIP returns the non loopback local IP of the host
func GetLocalIP() string {
addrs, err := net.InterfaceAddrs()
if err != nil {
return ""
}
for _, address := range addrs {
// check the address type and if it is not a loopback the display it
if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
if ipnet.IP.To4() != nil {
return ipnet.IP.String()
}
}
}
return ""
}
// GetClientPublicIP returns the client public IP
func GetClientPublicIP(r *http.Request) string {
defaultIp := "127.0.0.1"
ip := r.Header.Get("X-Real-IP")
if net.ParseIP(ip) != nil {
return ip
}
ip = r.Header.Get("X-Forward-For")
for _, i := range strings.Split(ip, ",") {
if net.ParseIP(i) != nil {
return i
}
}
ip, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
return defaultIp
}
if net.ParseIP(ip) != nil {
return ip
}
return defaultIp
}