Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to capture traffic from multiple interfaces using pcap

In order to sniff from multiple interfaces using pcap, I would do the following (in pseudocode):

foreach interface:
    open a file descriptor using pcap_open_live()
    set the file descriptor to non-blocking

while true:
    check for a ready file descriptor using select() or an equivalent I/O multiplexer
    read data from every ready file descriptor using pcap_dispatch()
    handle EndOfStream or Errors and break out of loop if needed

Is this enough or are there some particular caveats to take into account ?

like image 699
ziu Avatar asked Nov 04 '22 12:11

ziu


2 Answers

Here is small C-Program snippet to use PCAP library to capture (sniff) network packets in promiscus (stealth) mode in the network.

#include <stdio.h>
#include <stdlib.h>
#include <pcap.h>  /* GIMME a libpcap plz! */
#include <errno.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>  

void callback(u_char *useless,const struct pcap_pkthdr* pkthdr,const u_char* packet)
{
  static int count = 1;
  printf("\nPacket number [%d], length of this packet is: %d\n", count++, pkthdr->len);
}

void pktinit(char *dev) /*function: for individual interface packet capturing*/
{
    char errbuf[PCAP_ERRBUF_SIZE];
    pcap_t* descr;
    struct bpf_program fp;        /* to hold compiled program */
    bpf_u_int32 pMask;            /* subnet mask */
    bpf_u_int32 pNet;             /* ip address*/
    pcap_if_t *alldevs, *d;
    char dev_buff[64] = {0};
    int i =0;
    pcap_lookupnet(dev, &pNet, &pMask, errbuf);
    descr = pcap_open_live(dev, BUFSIZ, 0,-1, errbuf);
    if(descr == NULL)
    {
        printf("pcap_open_live() failed due to [%s]\n", errbuf);
        return -1;
    }
    return 0;
}

int main(int argc, char **argv)
{
    int pid,i;
    if(argc < 2) /*command <eth0> [eth1]...*/
    {
        fprintf(strerr,"command needs ethernet name")
        return 0;
    }
    for(i = 1; i < argc; i++)
    {
        if((pid=fork()) != -1)
        {
            pktinit(argv[i])
        }
        else
        {
            fprintf(stderr,"pacp failed for: %s\n", argv[i]);
        }
    }
    return 0;
}

gcc file.c -lpcap

./file eth0 eth1 wlan0

like image 192
Rahul Raina Avatar answered Nov 09 '22 09:11

Rahul Raina


I ran into some issues trying to capture from particular interfaces with pcap and asked about it here. It seemed few were familiar with pcap. My issues, and an answer I finally got pointing out very helpful details, can be found here in the below link which you might find useful:

Confused by libcap (pcap) and wireless

like image 42
gnometorule Avatar answered Nov 09 '22 08:11

gnometorule