You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
cronsun/utils/local_ip.go

32 lines
536 B

package utils
import (
"fmt"
"net"
)
// 获取本机 ip
// 获取第一个非 loopback ip
func LocalIP() (net.IP, error) {
tables, err := net.Interfaces()
if err != nil {
return nil, err
}
for _, t := range tables {
addrs, err := t.Addrs()
if err != nil {
return nil, err
}
for _, a := range addrs {
ipnet, ok := a.(*net.IPNet)
if !ok || ipnet.IP.IsLoopback() {
continue
}
if v4 := ipnet.IP.To4(); v4 != nil {
return v4, nil
}
}
}
return nil, fmt.Errorf("cannot find local IP address")
}