Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading