|
| 1 | +//go:build linux && !amd64 && !arm64 |
| 2 | +// +build linux,!amd64,!arm64 |
| 3 | + |
| 4 | +package arp |
| 5 | + |
| 6 | +import ( |
| 7 | + "net" |
| 8 | + "os" |
| 9 | + "syscall" |
| 10 | + "unsafe" |
| 11 | + |
| 12 | + "golang.org/x/sys/unix" |
| 13 | +) |
| 14 | + |
| 15 | +// InjectArp injects an ARP entry into dev's ARP table |
| 16 | +// syscalls roughly based on https://www.unix.com/302447674-post3.html |
| 17 | +// see: |
| 18 | +// https://github.com/torvalds/linux/blob/8cf8821e15cd553339a5b48ee555a0439c2b2742/net/ipv4/arp.c#L1179 |
| 19 | +// https://github.com/torvalds/linux/blob/8cf8821e15cd553339a5b48ee555a0439c2b2742/net/ipv4/arp.c#L1024 |
| 20 | +func InjectArp(ip net.IP, mac net.HardwareAddr, flags int32, dev string) (err error) { |
| 21 | + fd, err := unix.Socket(unix.AF_INET, unix.SOCK_DGRAM, unix.IPPROTO_UDP) |
| 22 | + if err != nil { |
| 23 | + return |
| 24 | + } |
| 25 | + f := os.NewFile(uintptr(fd), "") |
| 26 | + defer f.Close() |
| 27 | + |
| 28 | + return InjectArpFd(uintptr(fd), ip, mac, flags, dev) |
| 29 | +} |
| 30 | + |
| 31 | +func InjectArpFd(fd uintptr, ip net.IP, mac net.HardwareAddr, flags int32, dev string) (err error) { |
| 32 | + arpReq := arpReq{ |
| 33 | + ArpPa: syscall.RawSockaddrInet4{ |
| 34 | + Family: syscall.AF_INET, |
| 35 | + }, |
| 36 | + //Flags: 0x02 | 0x04, // ATF_COM | ATF_PERM; |
| 37 | + Flags: flags, |
| 38 | + } |
| 39 | + copy(arpReq.ArpPa.Addr[:], ip.To4()) |
| 40 | + copy(arpReq.ArpHa.Data[:], mac) |
| 41 | + copy(arpReq.Dev[:], dev) |
| 42 | + |
| 43 | + _, _, errno := unix.Syscall(unix.SYS_IOCTL, fd, unix.SIOCSARP, uintptr(unsafe.Pointer(&arpReq))) |
| 44 | + if errno != 0 { |
| 45 | + return errno |
| 46 | + } |
| 47 | + |
| 48 | + return |
| 49 | +} |
0 commit comments