package network import ( "net" "github.com/pkg/errors" "github.com/wlynxg/anet" ) var ( _, lanA, _ = net.ParseCIDR("10.0.0.0/8") _, lanB, _ = net.ParseCIDR("172.16.0.0/12") _, lanC, _ = net.ParseCIDR("192.168.0.0/16") ) func GetLANIPv4Addrs() ([]string, error) { ips := make([]string, 0) addrs, err := anet.InterfaceAddrs() if err != nil { return nil, errors.WithStack(err) } for _, address := range addrs { if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() { ipv4 := ipnet.IP.To4() if ipv4 == nil { continue } isLAN := lanA.Contains(ipv4) || lanB.Contains(ipv4) || lanC.Contains(ipv4) if !isLAN { continue } ips = append(ips, ipv4.String()) } } return ips, nil } func FindPreferredLocalAddress(ips ...net.IP) (string, error) { localAddrs, err := anet.InterfaceAddrs() if err != nil { return "", errors.WithStack(err) } for _, addr := range localAddrs { if ipnet, ok := addr.(*net.IPNet); ok && !ipnet.IP.IsLoopback() { for _, ip := range ips { if ipnet.Contains(ip) { return ip.String(), nil } } } } return ips[0].String(), nil }