Skip to content

Commit

Permalink
filter loopback ip
Browse files Browse the repository at this point in the history
  • Loading branch information
Penglq committed Nov 26, 2020
1 parent fb45465 commit 1b52b45
Showing 1 changed file with 16 additions and 8 deletions.
24 changes: 16 additions & 8 deletions util/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,17 +69,25 @@ var localIP = ""

func LocalIP() string {
if localIP == "" {
addrs, err := net.InterfaceAddrs()
netInterfaces, err := net.Interfaces()
if err != nil {
logger.Errorf("get InterfaceAddress failed,err:%+v", err)
logger.Errorf("get Interfaces failed,err:%+v", err)
return ""
}
for _, address := range addrs {
if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
if ipnet.IP.To4() != nil {
localIP = ipnet.IP.String()
logger.Infof("InitLocalIp, LocalIp:%s", localIP)
break

for i := 0; i < len(netInterfaces); i++ {
if ((netInterfaces[i].Flags & net.FlagUp) != 0) && ((netInterfaces[i].Flags & net.FlagLoopback) == 0) {
addrs, err := netInterfaces[i].Addrs()
if err != nil {
logger.Errorf("get InterfaceAddress failed,err:%+v", err)
return ""
}
for _, address := range addrs {
if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() && ipnet.IP.To4() != nil {
localIP = ipnet.IP.String()
logger.Infof("InitLocalIp, LocalIp:%s", localIP)
break
}
}
}
}
Expand Down

0 comments on commit 1b52b45

Please sign in to comment.