Question

I am writing a program in C that reads packets using libpcap, and then outputs information such as the destination and source addresses. I am new to network programming, so I can't understand the output discrepancy that I am getting. I always get the correct destination MAC address, but incorrect source address.

Here is what the expected output is supposed to be:

Packet number: 1 Packet Len: 42 Dest MAC: ff:ff:ff:ff:ff:ff Source MAC: 0:2:2d:90:75:89

Here is my output:

Packet Len: 42 Dest MAC: ff:ff:ff:ff:ff:ff Source MAC: 0:0:c0:a8:1:1

I know that in the ethernet header the source address immediately follows the destination address, so I created my own struct to reflect this:

typedef struct __attribute__((__packed__)) EtherHeader {
   const struct ether_addr destAddr[6];
   const struct ether_addr sourceAddr[6];
   uint8_t protocol; 
}EtherHeader;

Here is a snippet of my code that attempts to get the addresses:

char *fileName = argv[1];
char errbuf[100];
const struct EtherHeader *eth;

pcap_t *handle = pcap_open_offline(fileName, errbuf);
struct pcap_pkthdr pktHdr = calloc(1, sizeof(struct pcap_pkthdr));
const u_char *nextPkt = pcap_next(handle, pktHdr); 
int packNum = 0;

nextPkt = pcap_next(handle, pktHdr); 
printf("Packet number: %d  Packet Len: %d\n", packNum, pktHdr->len);
eth = (EtherHeader *)nextPkt;
printf("Dest MAC: %s\n", ether_ntoa(eth->destAddr));
printf("Source MAC: %s\n", ether_ntoa(eth->sourceAddr));

I also need to determine what protocol the packet contains. How would I get to the packet segment that has that? Is it the remaining two bytes in the header?

Any additional things I should watch out for would be greatly appreciated.

Was it helpful?

Solution

struct ether_addr is already defined as a struct containing 6 bytes, so you should replace

const struct ether_addr destAddr[6];
const struct ether_addr sourceAddr[6];

by

const struct ether_addr destAddr;
const struct ether_addr sourceAddr;

Note that you need an address-of operator & when printing the EtherNet addresses:

printf("Dest MAC: %s\n", ether_ntoa(&eth->destAddr));
printf("Source MAC: %s\n", ether_ntoa(&eth->sourceAddr));

(What happened in your case that the destination address what put into destAddr[0], the source address into destAddr[1] and the protocol into the first byte of destAddr[2].)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top