This commit is contained in:
david.yan 2025-04-08 15:20:34 +08:00
commit f7948263c5
1 changed files with 45 additions and 13 deletions

View File

@ -9,6 +9,7 @@ import (
"net/http"
"os"
"strconv"
"strings"
)
func IsPublicIP(ipString string) bool {
@ -32,24 +33,55 @@ func IsPublicIP(ipString string) bool {
}
// Get Location IP .
func GetLocationIP() string {
addrs, err := net.InterfaceAddrs()
func GetLocationIP() (localIp string) {
localIp = "127.0.0.1"
// Get all network interfaces
interfaces, err := net.Interfaces()
if err != nil {
return ""
return
}
ip := ""
for _, a := range addrs {
if ipnet, ok := a.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
if ipnet.IP.To4() != nil {
ip = ipnet.IP.String()
break
for _, iface := range interfaces {
// Skip the loopback interface
if iface.Flags&net.FlagLoopback != 0 {
continue
}
// 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 ip
return
}
func LocalIPv4s() ([]string, error) {