1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
| /************************************************************************* > File Name : pcap_example.c > Author : TL Song > EMail : songtianlun@frytea.com > Created Time : Thu Feb 18 18:57:20 2021 ************************************************************************/ int main() { char err_buf[PCAP_ERRBUF_SIZE]; struct bpf_program fp_recv; /* The compiled filter expression */ char filter_recv[] = RECV_FILTER; /* The filter expression (filter 53 port)*/ pcap_t *handle_recv; pcap_t *handle_recv_send; bpf_u_int32 mask_recv; /* The netmask of our sniffing device */ bpf_u_int32 net_recv; /* The IP of our sniffing device */ u_char *pkt_data = NULL; int rst; struct pcap_pkthdr header; struct pcap_pkthdr *p_header = &header; printf("Recv Device: %s\n", RECV_DEVICE); /*Step1, Open the session in promiscuous mode*/ handle_recv = pcap_open_live(RECV_DEVICE, BUFSIZ, 1, 1, err_buf); if (handle_recv == NULL) { fprintf(stderr, "Couldn't open device %s: %s\n", RECV_DEVICE, err_buf); return 0; } handle_recv_send = pcap_open_live(RECV_DEVICE_SEND, BUFSIZ, 1, 1, err_buf); if (handle_recv_send == NULL) { printf("Couldn't open device %s: %s\n", RECV_DEVICE_SEND, err_buf); return 0; } /*Step2, get network mask*/ if (pcap_lookupnet(RECV_DEVICE, &net_recv, &mask_recv, err_buf) == -1) { fprintf(stderr, "Can't get netmask for device %s\n", RECV_DEVICE); net_recv = 0; mask_recv = 0; } /* Step3, Compile and apply the filter */ if (pcap_compile(handle_recv, &fp_recv, filter_recv, 0, net_recv) == -1) { fprintf(stderr, "Couldn't parse filter %s: %s\n", filter_recv, pcap_geterr(handle_recv)); return 0; } if (pcap_setfilter(handle_recv, &fp_recv) == -1) { fprintf(stderr, "Couldn't install filter %s: %s\n", filter_recv, pcap_geterr(handle_recv)); return 0; } /* Step4, get frame. */ while(1){ pkt_data = (unsigned char * )pcap_next(handle_recv, p_header); rst = pcap_sendpacket(handle_recv_send, pkt_data, p_header->caplen); printf("Send to %s ret : %d\n", RECV_DEVICE_SEND, rst); } /* Step5, cleanup */ pcap_freecode(&fp_recv); pcap_close(handle_recv); pcap_close(handle_recv_send); dPrint("Capture complete."); return 0; }
|