c语言指定网口捕获数据包--使用libpcap包

/*
Listing 2. Simple sniffer
To compile: gcc simplesniffer.c -o simplesinffer -lpcap
*/

#include <stdio.h>
#include <pcap.h>
 
int main(int argc, char **argv)
{
	system("clear");
	pcap_t *fp;
 
	char errbuf[PCAP_ERRBUF_SIZE];
	pcap_t *descr= pcap_open_offline("/home/IPS/test.pcap",errbuf);
	const u_char * packet;
 
	struct pcap_pkthdr hdr;
 
	packet = pcap_next(descr, &hdr);
	//printf("packet: %s\n",packet);
	fflush(stdout);
		/* Open the output device */
		if ( (fp= pcap_open_live("eth3", 100, 1,1000,errbuf ) ) == NULL)
		{
			fprintf(stderr,"\nUnable to open the adapter. %s is not supported \n", "eth3");
			return 0;
		}
			printf("open the output device success!\n");
			getchar();
			while (packet)
			{
				unsigned packetSize= hdr.len;
				printf("packeSize is :%d\n",packetSize);
				unsigned i=0;
				/*				
				for (i=0; i< packetSize;i++)
				{
					//printf("now i is %d\n",i);
					//sleep(2);
				}
 				*/
				//pcap_sendpacket(sp->handle.pcap, data, (int)len);
				
				pcap_sendpacket(fp, packet, packetSize);
				packet = pcap_next(descr, &hdr);
				printf("send packet over!:%s \n",descr);
			}
		pcap_close(descr);
		return 0;
}


complie:gcc simplesniffer.c -o simplesinffer -lpcap



你可能感兴趣的:(C语言,libpcap,捕获数据包)