Skip to content

Commit

Permalink
Fix interface srcIP
Browse files Browse the repository at this point in the history
  • Loading branch information
v-byte-cpu committed Mar 10, 2021
1 parent a02b6ea commit 92ff7f4
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 6 deletions.
3 changes: 3 additions & 0 deletions command/arp.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,9 @@ var arpCmd = &cobra.Command{
if iface, err = net.InterfaceByName(interfaceFlag); err != nil {
return err
}
if srcIP, err = ip.GetSubnetInterfaceIP(iface, dstSubnet); err != nil {
return err
}
} else {
if iface, srcIP, err = ip.GetSubnetInterface(dstSubnet); err != nil {
return err
Expand Down
24 changes: 18 additions & 6 deletions pkg/ip/ip.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,21 +39,33 @@ func ParseIPNet(subnet string) (*net.IPNet, error) {
}

func GetSubnetInterface(dstSubnet *net.IPNet) (*net.Interface, net.IP, error) {
dstSubnetIP := dstSubnet.IP.Mask(dstSubnet.Mask)
ifaces, err := net.Interfaces()
if err != nil {
return nil, nil, err
}
for _, iface := range ifaces {
addrs, err := iface.Addrs()
iface := iface
ifaceIP, err := GetSubnetInterfaceIP(&iface, dstSubnet)
if err != nil {
return nil, nil, err
}
for _, addr := range addrs {
if ipnet, ok := addr.(*net.IPNet); ok && ipnet.Contains(dstSubnetIP) {
return &iface, ipnet.IP.To4(), nil
}
if ifaceIP != nil {
return &iface, ifaceIP.To4(), nil
}
}
return nil, nil, ErrSubnetInterface
}

func GetSubnetInterfaceIP(iface *net.Interface, dstSubnet *net.IPNet) (net.IP, error) {
dstSubnetIP := dstSubnet.IP.Mask(dstSubnet.Mask)
addrs, err := iface.Addrs()
if err != nil {
return nil, err
}
for _, addr := range addrs {
if ipnet, ok := addr.(*net.IPNet); ok && ipnet.Contains(dstSubnetIP) {
return ipnet.IP.To4(), nil
}
}
return nil, nil
}

0 comments on commit 92ff7f4

Please sign in to comment.