The best place to do this is to extract the required code from the tcpdump source, which as far as I'm concerned basically is both the how-to guide for libpcap and a networking introduction all in one.
Anyway, what you need is a packet handling function as you've gathered from pcap_open_live
. You will also need to create another thread or process because pcap_open_live
will block the current thread whilst it works.
Now, the packet handler function looks like this:
void packethandler( u_char *args, const struct pcap_pkthdr* pkthdr, const u_char* packet )
{
// ... allocs etc
// these instructions convert the "packet" string
// to a struct and determine it's type, a setting in
// the ethernet header.
eptr = (struct ether_header *) packet;
ether_type = ntohs(eptr->ether_type);
// ...
// these two functions extract the mac addresses
// into appropriately alloc'd strings.
// ether_ntoa converts the binary representation
// of the mac address into a string
snprintf(ethernet_shost, 20, "%s", ether_ntoa((struct ether_addr *)eptr->ether_shost));
snprintf(ethernet_dhost, 20, "%s", ether_ntoa((struct ether_addr *)eptr->ether_dhost));
// carry on...
}
This will get you the mac address as a string. Be warned, however, networking isn't easy. You need to know what you're doing with binary strings of information, casting etc and you need to know what the numbers and options mean. If the tcpdump source looks complicated, it is because networking is complicated. Also, I haven't listed the headers you need to achieve this process. There are pcap tutorials out there; I suggest you take your time to read them. My simply giving you an answer won't teach you networking.
Also, this function is incomplete. You will need the appropriate allocations for the storage arrays (pcap being a C library you may want to use char*
rather than string
then extract back to string
later).