Home > Net >  packet socket not receiving data
packet socket not receiving data

Time:05-21

I have the following C code that is supposed to await any packet on ethernet device eth0, including IPv6 multicast messages.

I am using a packet(7) socket here, as my underlying code is handling the layers. Hence, I want to receive all packets on that socket.

The communication to the other host is established via two IPv6 multicast messages back and forth and a subsequent TCP-based communication.

#include <sys/socket.h>
#include <linux/if_packet.h>
#include <netinet/if_ether.h>
#include <stdio.h>
#include <string.h>

int main(void) {
    int fd = socket(AF_PACKET, SOCK_RAW, 0);
    if (fd < 0)
    {
        perror("cannot open socket");
    }

    struct sockaddr_ll sll;
    memset(&sll, 0, sizeof(sll));
    sll.sll_family   = AF_PACKET;
    sll.sll_ifindex  = if_nametoindex("eth0");
    sll.sll_protocol = ETH_P_ALL;

    if (bind(fd, (struct sockaddr*)&sll, sizeof(sll)) < 0)
    {
        perror("cannot bind socket to device");
        return 1;
    }

    while(1) {
        char *recvBuf[1518];
        struct sockaddr_ll saddr;
        socklen_t saddr_size = sizeof(saddr);

        size_t len = recvfrom(fd, recvBuf, 1518, 0, (struct sockaddr*)&saddr, &saddr_size);

        // PRINTOUT HERE
    }

    close(fd);

    return 0;
}

I compile on my debian machine like that:

gcc my_sniffer.c -o test.bin
setcap 'cap_net_admin,cap_net_raw ep' ./test.bin
./test.bin

The binary starts up. However, no packet is received.

Running tcpdump -i eth0 -w test.pcap, yields in a received IPv6 multicast message.

What am I missing here? Is the code off? Wrong socket in use?

CodePudding user response:

In this line:

sll.sll_protocol = ETH_P_ALL;

you forgot to use htons

  • Related