| 1 | package arping |
| 2 | |
| 3 | import ( |
| 4 | "errors" |
| 5 | "fmt" |
| 6 | "net" |
| 7 | ) |
| 8 | |
| 9 | func findIPInNetworkFromIface(dstIP net.IP, iface net.Interface) (net.IP, error) { |
| 10 | addrs, err := iface.Addrs() |
| 11 | |
| 12 | if err != nil { |
| 13 | return nil, err |
| 14 | } |
| 15 | |
| 16 | for _, a := range addrs { |
| 17 | if ipnet, ok := a.(*net.IPNet); ok { |
| 18 | if ipnet.Contains(dstIP) { |
| 19 | return ipnet.IP, nil |
| 20 | } |
| 21 | } |
| 22 | } |
| 23 | return nil, fmt.Errorf("iface: '%s' can't reach ip: '%s'", iface.Name, dstIP) |
| 24 | } |
| 25 | |
| 26 | func findUsableInterfaceForNetwork(dstIP net.IP) (*net.Interface, error) { |
| 27 | ifaces, err := net.Interfaces() |
| 28 | |
| 29 | if err != nil { |
| 30 | return nil, err |
| 31 | } |
| 32 | |
| 33 | isDown := func(iface net.Interface) bool { |
| 34 | return iface.Flags&1 == 0 |
| 35 | } |
| 36 | |
| 37 | hasAddressInNetwork := func(iface net.Interface) bool { |
| 38 | if _, err := findIPInNetworkFromIface(dstIP, iface); err != nil { |
| 39 | return false |
| 40 | } |
| 41 | return true |
| 42 | } |
| 43 | |
| 44 | verboseLog.Println("search usable interface") |
| 45 | logIfaceResult := func(msg string, iface net.Interface) { |
| 46 | verboseLog.Printf("%10s: %6s %18s %s", msg, iface.Name, iface.HardwareAddr, iface.Flags) |
| 47 | } |
| 48 | |
| 49 | for _, iface := range ifaces { |
| 50 | if isDown(iface) { |
| 51 | logIfaceResult("DOWN", iface) |
| 52 | continue |
| 53 | } |
| 54 | |
| 55 | if !hasAddressInNetwork(iface) { |
| 56 | logIfaceResult("OTHER NET", iface) |
| 57 | continue |
| 58 | } |
| 59 | |
| 60 | logIfaceResult("USABLE", iface) |
| 61 | return &iface, nil |
| 62 | } |
| 63 | return nil, errors.New("no usable interface found") |
| 64 | } |