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