pcap简单抓包程序框架

  • Post author:
  • Post category:其他


/* meng shi pcap use  
   mengshi19860812@163.com  */

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "pcap.h"

void pkt_callback (u_char *arg, const struct pcap_pkthdr *pkt_hd, const u_char *pkt_content);


int
main (int argc, char **argv)
{
		pcap_t *pt;
    /* find device.  */
		char *dev = argv[1];
		char errbuf[PCAP_ERRBUF_SIZE];
		struct bpf_program filter;
		char *filter_exp;
		bpf_u_int32 mask, net;

		if (*argv[2] == 'p')
			{
				filter_exp = "port 8900";
			}
		else
			{
				filter_exp = "";
			}

		/* net is not ip, it is net number, net & msak.  */
		if (pcap_lookupnet (dev, &net, &mask, errbuf) == -1)
			{
				fprintf (stderr, "Could't get net mask for device %s:%s\n", dev, errbuf);
				net = mask = 0;
				goto J_EXT;
			}

		if ((pt = pcap_open_live (dev, BUFSIZ, 1, 1000, errbuf)) == NULL)
			{
				fprintf (stderr, "Could't open default device:%s\n", errbuf);
				goto J_EXT;
			}

		if (pcap_compile (pt, &filter, filter_exp, 0, net) == -1)
			{
				fprintf (stderr, "Could't parse filter %s:%s\n", filter_exp, pcap_geterr (pt));
				goto J_EXT;
			}

		if (pcap_setfilter (pt, &filter) == -1)
			{
				fprintf (stderr, "Could't install filter %s:%s\n", filter_exp, pcap_geterr (pt));
				goto J_EXT;
			}

		if (pcap_loop (pt, -1, pkt_callback, NULL) == -1)
			{
				perror ("pcap_loop");
				exit (2);
			}

		pcap_close (pt);

J_EXT:
		exit (0); 
}

/* pkt_content must yourself parse  */
void
pkt_callback (u_char *arg, const struct pcap_pkthdr *pkt_hd, const u_char *pkt_content)
{
		time_t t;
		t = pkt_hd->ts.tv_sec;
		printf ("%d, %d, %s", pkt_hd->caplen, pkt_hd->len, ctime (&t));
}



版权声明:本文为u011115454原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。