csocketsraw-sockets

can't read arp packets in c


i have the following simple code to capture all the arp packet sent to my device but it doesn't print anything

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <net/ethernet.h>

int main(){
        int sock;
        char recvbuf[2048];
        if((sock=socket(PF_PACKET,SOCK_DGRAM,htons(ETH_P_ARP)))==-1){
                perror("socket error");
                return -1;
        }
        for(;;){
                if(recvfrom(sock,recvbuf,sizeof(recvbuf),0,NULL,NULL)==-1){
                        perror("recvfrom error");
                }
                struct ether_header *e;
                e=(struct ether_header *)recvbuf;
                printf("arp from :%s\n",e->ether_shost);
        }
}

the output is like:

arp from :
arp from :
arp from :
arp from :
arp from :

Solution

  • A string, to be printed with %s, is a sequence of characters terminated with the special null-terminator character '\0'.

    The data in e->ether_shost is a series of six bytes, not characters, not null-terminated, and you need to print them one by one as small integers (usually in hexadecimal notation):

    printf("%02hhx:%02hhx:%02hhx:%02hhx:%02hhx:%02hhx\n",
        e->ether_shost[0], e->ether_shost[1], e->ether_shost[2],
        e->ether_shost[3], e->ether_shost[4], e->ether_shost[5]);
    

    For an explanation of the format used, see e.g. this printf reference.