Main Page | Modules | Data Structures | File List | Data Fields | Globals | Related Pages

Gathering Statistics on the network traffic
[WinPcap tutorial: a step by step guide to using WinPcap]

This lesson shows another advanced feature of WinPcap: the ability to collect statistics about network traffic. The statistical engine makes use of the kernel-level packet filter to efficiently classify the incoming packet. You can take a look at the NPF driver internals manual if you want to know more details.

In order to use this feature, the programmer must open an adapter and put it in statistical mode. This can be done with pcap_setmode(). In particular, MODE_STAT must be used as the mode argument of this function.

With statistical mode, making an application that monitors the TCP traffic load is a matter of few lines of code. The following sample shows how to do it.

/* * Copyright (c) 1999 - 2005 NetGroup, Politecnico di Torino (Italy) * Copyright (c) 2005 - 2006 CACE Technologies, Davis (California) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the Politecnico di Torino, CACE Technologies * nor the names of its contributors may be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include <stdlib.h> #include <stdio.h> #include <pcap.h> void usage(); void dispatcher_handler(u_char *, const struct pcap_pkthdr *, const u_char *); void main(int argc, char **argv) { pcap_t *fp; char errbuf[PCAP_ERRBUF_SIZE]; struct timeval st_ts; u_int netmask; struct bpf_program fcode; /* Check the validity of the command line */ if (argc != 2) { usage(); return; } /* Open the output adapter */ if ( (fp= pcap_open(argv[1], 100, PCAP_OPENFLAG_PROMISCUOUS, 1000, NULL, errbuf) ) == NULL) { fprintf(stderr,"\nUnable to open adapter %s.\n", errbuf); return; } /* Don't care about netmask, it won't be used for this filter */ netmask=0xffffff; //compile the filter if (pcap_compile(fp, &fcode, "tcp", 1, netmask) <0 ) { fprintf(stderr,"\nUnable to compile the packet filter. Check the syntax.\n"); /* Free the device list */ return; } //set the filter if (pcap_setfilter(fp, &fcode)<0) { fprintf(stderr,"\nError setting the filter.\n"); pcap_close(fp); /* Free the device list */ return; } /* Put the interface in statstics mode */ if (pcap_setmode(fp, MODE_STAT)<0) { fprintf(stderr,"\nError setting the mode.\n"); pcap_close(fp); /* Free the device list */ return; } printf("TCP traffic summary:\n"); /* Start the main loop */ pcap_loop(fp, 0, dispatcher_handler, (PUCHAR)&st_ts); pcap_close(fp); return; } void dispatcher_handler(u_char *state, const struct pcap_pkthdr *header, const u_char *pkt_data) { struct timeval *old_ts = (struct timeval *)state; u_int delay; LARGE_INTEGER Bps,Pps; struct tm *ltime; char timestr[16]; time_t local_tv_sec; /* Calculate the delay in microseconds from the last sample. */ /* This value is obtained from the timestamp that the associated with the sample. */ delay=(header->ts.tv_sec - old_ts->tv_sec) * 1000000 - old_ts->tv_usec + header->ts.tv_usec; /* Get the number of Bits per second */ Bps.QuadPart=(((*(LONGLONG*)(pkt_data + 8)) * 8 * 1000000) / (delay)); /* ^ ^ | | | | | | converts bytes in bits -- | | delay is expressed in microseconds -- */ /* Get the number of Packets per second */ Pps.QuadPart=(((*(LONGLONG*)(pkt_data)) * 1000000) / (delay)); /* Convert the timestamp to readable format */ local_tv_sec = header->ts.tv_sec; ltime=localtime(&local_tv_sec); strftime( timestr, sizeof timestr, "%H:%M:%S", ltime); /* Print timestamp*/ printf("%s ", timestr); /* Print the samples */ printf("BPS=%I64u ", Bps.QuadPart); printf("PPS=%I64u\n", Pps.QuadPart); //store current timestamp old_ts->tv_sec=header->ts.tv_sec; old_ts->tv_usec=header->ts.tv_usec; } void usage() { printf("\nShows the TCP traffic load, in bits per second and packets per second.\nCopyright (C) 2002 Loris Degioanni.\n"); printf("\nUsage:\n"); printf("\t tcptop adapter\n"); printf("\t You can use \"WinDump -D\" if you don't know the name of your adapters.\n"); exit(0); }
00001 /* 00002 * Copyright (c) 1999 - 2005 NetGroup, Politecnico di Torino (Italy) 00003 * Copyright (c) 2005 - 2006 CACE Technologies, Davis (California) 00004 * All rights reserved. 00005 * 00006 * Redistribution and use in source and binary forms, with or without 00007 * modification, are permitted provided that the following conditions 00008 * are met: 00009 * 00010 * 1. Redistributions of source code must retain the above copyright 00011 * notice, this list of conditions and the following disclaimer. 00012 * 2. Redistributions in binary form must reproduce the above copyright 00013 * notice, this list of conditions and the following disclaimer in the 00014 * documentation and/or other materials provided with the distribution. 00015 * 3. Neither the name of the Politecnico di Torino, CACE Technologies 00016 * nor the names of its contributors may be used to endorse or promote 00017 * products derived from this software without specific prior written 00018 * permission. 00019 * 00020 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 00021 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 00022 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 00023 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 00024 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 00025 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 00026 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 00027 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 00028 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 00029 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 00030 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 00031 * 00032 */ 00033 00034 #include <stdlib.h> 00035 #include <stdio.h> 00036 00037 #include <pcap.h> 00038 00039 void usage(); 00040 00041 void dispatcher_handler(u_char *, const struct pcap_pkthdr *, const u_char *); 00042 00043 00044 void main(int argc, char **argv) 00045 { 00046 pcap_t *fp; 00047 char errbuf[PCAP_ERRBUF_SIZE]; 00048 struct timeval st_ts; 00049 u_int netmask; 00050 struct bpf_program fcode; 00051 00052 /* Check the validity of the command line */ 00053 if (argc != 2) 00054 { 00055 usage(); 00056 return; 00057 } 00058 00059 /* Open the output adapter */ 00060 if ( (fp= pcap_open(argv[1], 100, PCAP_OPENFLAG_PROMISCUOUS, 1000, NULL, errbuf) ) == NULL) 00061 { 00062 fprintf(stderr,"\nUnable to open adapter %s.\n", errbuf); 00063 return; 00064 } 00065 00066 /* Don't care about netmask, it won't be used for this filter */ 00067 netmask=0xffffff; 00068 00069 //compile the filter 00070 if (pcap_compile(fp, &fcode, "tcp", 1, netmask) <0 ) 00071 { 00072 fprintf(stderr,"\nUnable to compile the packet filter. Check the syntax.\n"); 00073 /* Free the device list */ 00074 return; 00075 } 00076 00077 //set the filter 00078 if (pcap_setfilter(fp, &fcode)<0) 00079 { 00080 fprintf(stderr,"\nError setting the filter.\n"); 00081 pcap_close(fp); 00082 /* Free the device list */ 00083 return; 00084 } 00085 00086 /* Put the interface in statstics mode */ 00087 if (pcap_setmode(fp, MODE_STAT)<0) 00088 { 00089 fprintf(stderr,"\nError setting the mode.\n"); 00090 pcap_close(fp); 00091 /* Free the device list */ 00092 return; 00093 } 00094 00095 00096 printf("TCP traffic summary:\n"); 00097 00098 /* Start the main loop */ 00099 pcap_loop(fp, 0, dispatcher_handler, (PUCHAR)&st_ts); 00100 00101 pcap_close(fp); 00102 return; 00103 } 00104 00105 void dispatcher_handler(u_char *state, const struct pcap_pkthdr *header, const u_char *pkt_data) 00106 { 00107 struct timeval *old_ts = (struct timeval *)state; 00108 u_int delay; 00109 LARGE_INTEGER Bps,Pps; 00110 struct tm *ltime; 00111 char timestr[16]; 00112 time_t local_tv_sec; 00113 00114 /* Calculate the delay in microseconds from the last sample. */ 00115 /* This value is obtained from the timestamp that the associated with the sample. */ 00116 delay=(header->ts.tv_sec - old_ts->tv_sec) * 1000000 - old_ts->tv_usec + header->ts.tv_usec; 00117 /* Get the number of Bits per second */ 00118 Bps.QuadPart=(((*(LONGLONG*)(pkt_data + 8)) * 8 * 1000000) / (delay)); 00119 /* ^ ^ 00120 | | 00121 | | 00122 | | 00123 converts bytes in bits -- | 00124 | 00125 delay is expressed in microseconds -- 00126 */ 00127 00128 /* Get the number of Packets per second */ 00129 Pps.QuadPart=(((*(LONGLONG*)(pkt_data)) * 1000000) / (delay)); 00130 00131 /* Convert the timestamp to readable format */ 00132 local_tv_sec = header->ts.tv_sec; 00133 ltime=localtime(&local_tv_sec); 00134 strftime( timestr, sizeof timestr, "%H:%M:%S", ltime); 00135 00136 /* Print timestamp*/ 00137 printf("%s ", timestr); 00138 00139 /* Print the samples */ 00140 printf("BPS=%I64u ", Bps.QuadPart); 00141 printf("PPS=%I64u\n", Pps.QuadPart); 00142 00143 //store current timestamp 00144 old_ts->tv_sec=header->ts.tv_sec; 00145 old_ts->tv_usec=header->ts.tv_usec; 00146 } 00147 00148 00149 void usage() 00150 { 00151 00152 printf("\nShows the TCP traffic load, in bits per second and packets per second.\nCopyright (C) 2002 Loris Degioanni.\n"); 00153 printf("\nUsage:\n"); 00154 printf("\t tcptop adapter\n"); 00155 printf("\t You can use \"WinDump -D\" if you don't know the name of your adapters.\n"); 00156 00157 exit(0); 00158 }

Before enabling statistical mode, the user has the option to set a filter that defines the subset of network traffic that will be monitored. See the paragraph on the Filtering expression syntax for details. If no filter has been set, all of the traffic will be monitored.

Once

the interface descriptor starts to work in statistical mode. Notice the fourth parameter (to_ms) of pcap_open(): it defines the interval among the statistical samples. The callback function receives the samples calculated by the driver every to_ms milliseconds. These samples are encapsulated in the second and third parameters of the callback function, as shown in the following figure:

stats_wpcap.gif
Two 64-bit counters are provided: the number of packets and the amount of bytes received during the last interval.

In the example, the adapter is opened with a timeout of 1000 ms. This means that dispatcher_handler() is called once per second. At this point a filter that keeps only tcp packets is compiled and set. Then pcap_setmode() and pcap_loop() are called. Note that a struct timeval pointer is passed to pcap_loop() as the user parameter. This structure will be used to store a timestamp in order to calculate the interval between two samples. dispatcher_handler()uses this interval to obtain the bits per second and the packets per second and then prints these values on the screen.

Note finally that this example is by far more efficient than a program that captures the packets in the traditional way and calculates statistics at user-level. Statistical mode requires the minumum amount of data copies and context switches and therefore the CPU is optimized. Moreover, a very small amount of memory is required.

<<< Previous


documentation. Copyright (c) 2002-2005 Politecnico di Torino. Copyright (c) 2005-2006 CACE Technologies. All rights reserved.