c语言指定网口转发数据包---使用libpcap包

sendPkt.c

#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;
}

编译命令:gcc -o sendpkt sendPkt.c -lpcap

实际测试,拿wireshark 抓包比对结果正确

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