add winpcap 4.0.2 from url http://www.winpcap.org/
[natblaster.git] / winpcap / Examples-pcap / basic_dump_ex / basic_dump_ex.c
blob36e6f2120745af8cba0377c09188ba4893cf97a1
1 #include "pcap.h"
4 int main()
6 pcap_if_t *alldevs;
7 pcap_if_t *d;
8 int inum;
9 int i=0;
10 pcap_t *adhandle;
11 int res;
12 char errbuf[PCAP_ERRBUF_SIZE];
13 struct tm *ltime;
14 char timestr[16];
15 struct pcap_pkthdr *header;
16 const u_char *pkt_data;
17 time_t local_tv_sec;
20 /* Retrieve the device list */
21 if(pcap_findalldevs(&alldevs, errbuf) == -1)
23 fprintf(stderr,"Error in pcap_findalldevs: %s\n", errbuf);
24 return -1;
27 /* Print the list */
28 for(d=alldevs; d; d=d->next)
30 printf("%d. %s", ++i, d->name);
31 if (d->description)
32 printf(" (%s)\n", d->description);
33 else
34 printf(" (No description available)\n");
37 if(i==0)
39 printf("\nNo interfaces found! Make sure WinPcap is installed.\n");
40 return -1;
43 printf("Enter the interface number (1-%d):",i);
44 scanf("%d", &inum);
46 if(inum < 1 || inum > i)
48 printf("\nInterface number out of range.\n");
49 /* Free the device list */
50 pcap_freealldevs(alldevs);
51 return -1;
54 /* Jump to the selected adapter */
55 for(d=alldevs, i=0; i< inum-1 ;d=d->next, i++);
57 /* Open the adapter */
58 if ((adhandle= pcap_open_live(d->name, // name of the device
59 65536, // portion of the packet to capture.
60 // 65536 grants that the whole packet will be captured on all the MACs.
61 1, // promiscuous mode (nonzero means promiscuous)
62 1000, // read timeout
63 errbuf // error buffer
64 )) == NULL)
66 fprintf(stderr,"\nUnable to open the adapter. %s is not supported by WinPcap\n", d->name);
67 /* Free the device list */
68 pcap_freealldevs(alldevs);
69 return -1;
72 printf("\nlistening on %s...\n", d->description);
74 /* At this point, we don't need any more the device list. Free it */
75 pcap_freealldevs(alldevs);
77 /* Retrieve the packets */
78 while((res = pcap_next_ex( adhandle, &header, &pkt_data)) >= 0){
80 if(res == 0)
81 /* Timeout elapsed */
82 continue;
84 /* convert the timestamp to readable format */
85 local_tv_sec = header->ts.tv_sec;
86 ltime=localtime(&local_tv_sec);
87 strftime( timestr, sizeof timestr, "%H:%M:%S", ltime);
89 printf("%s,%.6d len:%d\n", timestr, header->ts.tv_usec, header->len);
92 if(res == -1){
93 printf("Error reading the packets: %s\n", pcap_geterr(adhandle));
94 return -1;
97 pcap_close(adhandle);
98 return 0;