fix net getLocationIP
This commit is contained in:
parent
6ec06c2813
commit
b8f693ef82
58
utils/net.go
58
utils/net.go
|
@ -9,6 +9,7 @@ import (
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
func IsPublicIP(ipString string) bool {
|
func IsPublicIP(ipString string) bool {
|
||||||
|
@ -32,24 +33,55 @@ func IsPublicIP(ipString string) bool {
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get Location IP .
|
// Get Location IP .
|
||||||
func GetLocationIP() string {
|
func GetLocationIP() (localIp string) {
|
||||||
addrs, err := net.InterfaceAddrs()
|
localIp = "127.0.0.1"
|
||||||
|
// Get all network interfaces
|
||||||
|
interfaces, err := net.Interfaces()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return ""
|
return
|
||||||
}
|
}
|
||||||
ip := ""
|
|
||||||
for _, a := range addrs {
|
for _, iface := range interfaces {
|
||||||
if ipnet, ok := a.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
|
// Skip the loopback interface
|
||||||
if ipnet.IP.To4() != nil {
|
if iface.Flags&net.FlagLoopback != 0 {
|
||||||
ip = ipnet.IP.String()
|
continue
|
||||||
break
|
}
|
||||||
|
|
||||||
|
// Get addresses associated with the interface
|
||||||
|
addrs, err := iface.Addrs()
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, addr := range addrs {
|
||||||
|
// Check if the address is an IPNet
|
||||||
|
ipnet, ok := addr.(*net.IPNet)
|
||||||
|
if !ok || ipnet.IP.IsLoopback() {
|
||||||
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Get the IP address
|
||||||
|
ip := ipnet.IP.To4()
|
||||||
|
if ip == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// Skip IP addresses in the 169.254.x.x range
|
||||||
|
if strings.HasPrefix(ip.String(), "169.254") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// Skip IP addresses in the 169.254.x.x range
|
||||||
|
if strings.HasPrefix(ip.String(), "26.26") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// Return the first valid IP address found
|
||||||
|
return ip.String()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if ip == "" {
|
|
||||||
return ""
|
return
|
||||||
}
|
|
||||||
return ip
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func LocalIPv4s() ([]string, error) {
|
func LocalIPv4s() ([]string, error) {
|
||||||
|
|
Loading…
Reference in New Issue