7

I'm trying to read the link-layer packets received by my wifi-card using golang. The program I wrote compiles successfully and runs without any errors, but it seems to be stuck trying to read from the socket (syscall.Recvfrom(fd, data, 0 - At this point to be precise). What am i doing wrong?

PS: wlx34e894f77905 is the name of my wifi device.

My function which tries to read the packets:

func readFromSocket() {
    fd, error := syscall.Socket(syscall.AF_PACKET, syscall.SOCK_RAW, syscall.ETH_P_ALL)
    if error != nil {
        syscall.Close(fd)
        panic(error)
    }
    err := syscall.BindToDevice(fd, "wlx34e894f77905")
    if err != nil {
        syscall.Close(fd)
        panic(err)
    }
    data := make([]byte, 1024)
    for {
        syscall.Recvfrom(fd, data, 0)
        fmt.Println(data)
    }
}

netstat -r output:

default         _gateway        0.0.0.0         UG        0 0          0 wlx34e894f77905
link-local      0.0.0.0         255.255.0.0     U         0 0          0 wlx34e894f77905
172.17.0.0      0.0.0.0         255.255.0.0     U         0 0          0 docker0
172.18.0.0      0.0.0.0         255.255.0.0     U         0 0          0 br-3d5c8c113e89
192.168.0.0     0.0.0.0         255.255.255.0   U         0 0          0 wlx34e894f77905
ashishmax31
  • 151
  • 2
  • 12
  • Is your wireless device configured and your Internet traffic going through it while you are doing this? Please provide "netstat -r" output. – Jomu Apr 14 '20 at 11:05
  • @Jomu Yes the internet traffic is being routed through my wifi card. Editing the original question with the netstat output. – ashishmax31 Apr 14 '20 at 15:28
  • 1
    Many years ago I did similar work with the TAP device. The way you are doing this, IIRC, fights with kernel for this device, and you are losing there. The important thing here is what you want to achieve? Do you want to sniff traffic, or participate in it? If you want to sniff traffic, then you can look into how libpcap is doing it, and if you want to participate then TUN/TAP. – Jomu Apr 15 '20 at 14:54
  • Seems like the culprit was the byteorder. @Jomu – ashishmax31 Apr 15 '20 at 19:15

1 Answers1

7

like c/c++ code:

sock_raw=socket(AF_PACKET,SOCK_RAW,htons(ETH_P_ALL));

so, golang is:

syscall.Socket(syscall.AF_PACKET, syscall.SOCK_RAW, htons(syscall.ETH_P_ALL))

htons(syscall.ETH_P_ALL) => 0x0300 (little endian)

schain
  • 161
  • 2