add winpcap 4.0.2 from url http://www.winpcap.org/
[natblaster.git] / winpcap / Examples-pcap / basic_dump / basic_dump.c
blob9090c4588ad8cefd9ac074937f4438b53601e39e
1 #include "pcap.h"
3 /* prototype of the packet handler */
4 void packet_handler(u_char *param, const struct pcap_pkthdr *header, const u_char *pkt_data);
6 main()
8 pcap_if_t *alldevs;
9 pcap_if_t *d;
10 int inum;
11 int i=0;
12 pcap_t *adhandle;
13 char errbuf[PCAP_ERRBUF_SIZE];
15 /* Retrieve the device list */
16 if(pcap_findalldevs(&alldevs, errbuf) == -1)
18 fprintf(stderr,"Error in pcap_findalldevs: %s\n", errbuf);
19 exit(1);
22 /* Print the list */
23 for(d=alldevs; d; d=d->next)
25 printf("%d. %s", ++i, d->name);
26 if (d->description)
27 printf(" (%s)\n", d->description);
28 else
29 printf(" (No description available)\n");
32 if(i==0)
34 printf("\nNo interfaces found! Make sure WinPcap is installed.\n");
35 return -1;
38 printf("Enter the interface number (1-%d):",i);
39 scanf("%d", &inum);
41 if(inum < 1 || inum > i)
43 printf("\nInterface number out of range.\n");
44 /* Free the device list */
45 pcap_freealldevs(alldevs);
46 return -1;
49 /* Jump to the selected adapter */
50 for(d=alldevs, i=0; i< inum-1 ;d=d->next, i++);
52 /* Open the device */
53 /* Open the adapter */
54 if ((adhandle= pcap_open_live(d->name, // name of the device
55 65536, // portion of the packet to capture.
56 // 65536 grants that the whole packet will be captured on all the MACs.
57 1, // promiscuous mode (nonzero means promiscuous)
58 1000, // read timeout
59 errbuf // error buffer
60 )) == NULL)
62 fprintf(stderr,"\nUnable to open the adapter. %s is not supported by WinPcap\n", d->name);
63 /* Free the device list */
64 pcap_freealldevs(alldevs);
65 return -1;
68 printf("\nlistening on %s...\n", d->description);
70 /* At this point, we don't need any more the device list. Free it */
71 pcap_freealldevs(alldevs);
73 /* start the capture */
74 pcap_loop(adhandle, 0, packet_handler, NULL);
76 pcap_close(adhandle);
77 return 0;
81 /* Callback function invoked by libpcap for every incoming packet */
82 void packet_handler(u_char *param, const struct pcap_pkthdr *header, const u_char *pkt_data)
84 struct tm *ltime;
85 char timestr[16];
86 time_t local_tv_sec;
88 /* convert the timestamp to readable format */
89 local_tv_sec = header->ts.tv_sec;
90 ltime=localtime(&local_tv_sec);
91 strftime( timestr, sizeof timestr, "%H:%M:%S", ltime);
93 printf("%s,%.6d len:%d\n", timestr, header->ts.tv_usec, header->len);