package utils import ( "net" "github.com/go-errors/errors" ) func getLocalIP() (net.IP, error) { conn, err := net.Dial("udp", "1.0.0.1:53") if err != nil { return nil, err } defer conn.Close() host, _, err := net.SplitHostPort(conn.LocalAddr().String()) if err != nil { return nil, errors.Wrap(err, 0) } ip := net.ParseIP(host) if ip == nil { return nil, errors.Errorf("failed to parse IP address %q", host) } return ip, nil } func FindDefaultAdapter() (*net.Interface, error) { localIP, err := getLocalIP() if err != nil { return nil, errors.WrapPrefix(err, "failed to get local address", 0) } iflist, err := net.Interfaces() if err != nil { return nil, errors.WrapPrefix(err, "failed to get interface list", 0) } for _, iface := range iflist { addrs, err := iface.Addrs() if err != nil { continue } for _, addr := range addrs { ipnet, ok := addr.(*net.IPNet) if !ok { continue } if localIP.Equal(ipnet.IP) { return &iface, nil } } } return nil, errors.New("failed to find default adapter") }