You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
go-zero/core/netx/ip.go

40 lines
632 B
Go

4 years ago
package netx
import "net"
func InternalIp() string {
infs, err := net.Interfaces()
if err != nil {
return ""
}
for _, inf := range infs {
if isEthDown(inf.Flags) || isLoopback(inf.Flags) {
continue
}
addrs, err := inf.Addrs()
if err != nil {
continue
}
for _, addr := range addrs {
if ipnet, ok := addr.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
if ipnet.IP.To4() != nil {
return ipnet.IP.String()
}
}
}
}
return ""
}
func isEthDown(f net.Flags) bool {
return f&net.FlagUp != net.FlagUp
}
func isLoopback(f net.Flags) bool {
return f&net.FlagLoopback == net.FlagLoopback
}