mirror of
https://github.com/zeromicro/go-zero.git
synced 2025-01-24 01:30:25 +08:00
41 lines
670 B
Go
41 lines
670 B
Go
package netx
|
|
|
|
import "net"
|
|
|
|
// InternalIp returns an internal ip.
|
|
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
|
|
}
|