c++ winpcap开发(6)
既然我們能夠捕獲和過濾網絡流量,我們希望把我們的知識與一個簡單的“現實世界”應用程序一起使用。
在本課中,我們將從以前的課程中獲取代碼,并使用這些代碼構建更有用的程序。當前程序的主要目的是顯示如何解析和解釋捕獲的數據包的協議頭。生成的應用程序UDPdump打印了我們網絡上UDP流量的摘要。
我們選擇解析和顯示UDP協議,因為它比其他協議(如TCP)更易于訪問,因此是一個很好的初始示例。我們來看看代碼:
#include "pcap.h"/* 4 bytes IP address */ typedef struct ip_address{u_char byte1;u_char byte2;u_char byte3;u_char byte4; }ip_address;/* IPv4 header */ typedef struct ip_header{u_char ver_ihl; // Version (4 bits) + Internet header length (4 bits)u_char tos; // Type of service u_short tlen; // Total length u_short identification; // Identificationu_short flags_fo; // Flags (3 bits) + Fragment offset (13 bits)u_char ttl; // Time to liveu_char proto; // Protocolu_short crc; // Header checksumip_address saddr; // Source addressip_address daddr; // Destination addressu_int op_pad; // Option + Padding }ip_header;/* UDP header*/ typedef struct udp_header{u_short sport; // Source portu_short dport; // Destination portu_short len; // Datagram lengthu_short crc; // Checksum }udp_header;/* prototype of the packet handler */ void packet_handler(u_char *param, const struct pcap_pkthdr *header, const u_char *pkt_data);int main() { pcap_if_t *alldevs; pcap_if_t *d; int inum; int i=0; pcap_t *adhandle; char errbuf[PCAP_ERRBUF_SIZE]; u_int netmask; char packet_filter[] = "ip and udp"; struct bpf_program fcode;/* Retrieve the device list */if (pcap_findalldevs_ex(PCAP_SRC_IF_STRING, NULL, &alldevs, errbuf) == -1){fprintf(stderr,"Error in pcap_findalldevs: %s\n", errbuf);exit(1);}/* Print the list */for(d=alldevs; d; d=d->next){printf("%d. %s", ++i, d->name);if (d->description)printf(" (%s)\n", d->description);elseprintf(" (No description available)\n");}if(i==0){printf("\nNo interfaces found! Make sure WinPcap is installed.\n");return -1;}printf("Enter the interface number (1-%d):",i);scanf_s("%d", &inum);if(inum < 1 || inum > i){printf("\nInterface number out of range.\n");/* Free the device list */pcap_freealldevs(alldevs);return -1;}/* Jump to the selected adapter */for(d=alldevs, i=0; i< inum-1 ;d=d->next, i++);/* Open the adapter */if ( (adhandle= pcap_open(d->name, // name of the device65536, // portion of the packet to capture. // 65536 grants that the whole packet will be captured on all the MACs.PCAP_OPENFLAG_PROMISCUOUS, // promiscuous mode1000, // read timeoutNULL, // remote authenticationerrbuf // error buffer) ) == NULL){fprintf(stderr,"\nUnable to open the adapter. %s is not supported by WinPcap\n");/* Free the device list */pcap_freealldevs(alldevs);return -1;}/* Check the link layer. We support only Ethernet for simplicity. */if(pcap_datalink(adhandle) != DLT_EN10MB){fprintf(stderr,"\nThis program works only on Ethernet networks.\n");/* Free the device list */pcap_freealldevs(alldevs);return -1;}if(d->addresses != NULL)/* Retrieve the mask of the first address of the interface */netmask=((struct sockaddr_in *)(d->addresses->netmask))->sin_addr.S_un.S_addr;else/* If the interface is without addresses we suppose to be in a C class network */netmask=0xffffff; //compile the filterif (pcap_compile(adhandle, &fcode, packet_filter, 1, netmask) <0 ){fprintf(stderr,"\nUnable to compile the packet filter. Check the syntax.\n");/* Free the device list */pcap_freealldevs(alldevs);return -1;}//set the filterif (pcap_setfilter(adhandle, &fcode)<0){fprintf(stderr,"\nError setting the filter.\n");/* Free the device list */pcap_freealldevs(alldevs);return -1;}printf("\nlistening on %s...\n", d->description);/* At this point, we don't need any more the device list. Free it */pcap_freealldevs(alldevs);/* start the capture */pcap_loop(adhandle, 0, packet_handler, NULL);return 0; }/* Callback function invoked by libpcap for every incoming packet */ void packet_handler(u_char *param, const struct pcap_pkthdr *header, const u_char *pkt_data) {struct tm ltime;char timestr[16];ip_header *ih;udp_header *uh;u_int ip_len;u_short sport,dport;time_t local_tv_sec;/** Unused variable*/(VOID)(param);/* convert the timestamp to readable format */local_tv_sec = header->ts.tv_sec;localtime_s(<ime, &local_tv_sec);strftime( timestr, sizeof timestr, "%H:%M:%S", <ime);/* print timestamp and length of the packet */printf("%s.%.6d len:%d ", timestr, header->ts.tv_usec, header->len);/* retireve the position of the ip header */ih = (ip_header *) (pkt_data +14); //length of ethernet header/* retireve the position of the udp header */ip_len = (ih->ver_ihl & 0xf) * 4;uh = (udp_header *) ((u_char*)ih + ip_len);/* convert from network byte order to host byte order */sport = ntohs( uh->sport );dport = ntohs( uh->dport );/* print ip addresses and udp ports */printf("%d.%d.%d.%d.%d -> %d.%d.%d.%d.%d\n",ih->saddr.byte1,ih->saddr.byte2,ih->saddr.byte3,ih->saddr.byte4,sport,ih->daddr.byte1,ih->daddr.byte2,ih->daddr.byte3,ih->daddr.byte4,dport); }首先,我們將過濾器設置為“ip和udp”。以這種方式,我們確信packet_handler()只能通過IPv4接收UDP數據包:這簡化了解析并提高了程序的效率。
我們還創建了幾個描述IP和UDP頭文件的結構體。這些結構體被packet_handler()用于正確定位各種標題字段。
packet_handler()雖然限于單個協議解析器(UDP over IPv4),但是顯示了像tcpdump / WinDump這樣復雜的“嗅探器”如何解碼網絡流量。由于我們對MAC頭不感興趣,所以我們跳過它。為了簡單起見,在開始捕獲之前,我們使用pcap_datalink()檢查MAC層,以確保我們正在處理以太網。這樣我們可以確定MAC頭部正好是14個字節。
IP頭位于MAC頭之后。我們將從IP頭提取IP源和目標地址。
由于IP頭不具有固定的長度,所以到達UDP頭是有點復雜的。因此,我們使用IP頭的長度字段來知道它的大小。一旦我們知道UDP頭的位置,我們就提取了源和目標端口。
提取的值打印在屏幕上,結果如下:
1. \Device\Packet_{A7FD048A-5D4B-478E-B3C1-34401AC3B72F} (Xircom t 10/100 Adapter)?
Enter the interface number (1-2):1
listening on Xircom CardBus Ethernet 10/100 Adapter...?
16:13:15.312784 len:87 130.192.31.67.2682 -> 130.192.3.21.53?
16:13:15.314796 len:137 130.192.3.21.53 -> 130.192.31.67.2682?
16:13:15.322101 len:78 130.192.31.67.2683 -> 130.192.3.21.53?
最后3行中的每一行代表不同的數據包。
總結
以上是生活随笔為你收集整理的c++ winpcap开发(6)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 数据的结构和运算(求和,最大和最小)
- 下一篇: LeetCode 445 分发饼干