00001 #include "pcap.h" 00002 00003 /* prototype of the packet handler */ 00004 void packet_handler(u_char *param, const struct pcap_pkthdr *header, const u_char *pkt_data);
00005
00006 main()
00007 {
00008 pcap_if_t *alldevs;
00009 pcap_if_t *d;
00010 int inum;
00011 int i=0;
00012 pcap_t *adhandle;
00013 char errbuf[PCAP_ERRBUF_SIZE];
00014
00015 /* Retrieve the device list */ 00016 if (pcap_findalldevs(&alldevs, errbuf) == -1)
00017 {
00018 fprintf(stderr,"Error in pcap_findalldevs: %s\n", errbuf);
00019 exit(1);
00020 }
00021
00022 /* Print the list */ 00023 for(d=alldevs; d; d=d->next)
00024 {
00025 printf("%d. %s", ++i, d->name);
00026 if (d->description)
00027 printf(" (%s)\n", d->description);
00028 else 00029 printf(" (No description available)\n");
00030 }
00031
00032 if(i==0)
00033 {
00034 printf("\nNo interfaces found! Make sure WinPcap is installed.\n");
00035 return -1;
00036 }
00037
00038 printf("Enter the interface number (1-%d):",i);
00039 scanf("%d", &inum);
00040
00041 if(inum < 1 || inum > i)
00042 {
00043 printf("\nInterface number out of range.\n");
00044 /* Free the device list */ 00045 pcap_freealldevs(alldevs);
00046 return -1;
00047 }
00048
00049 /* Jump to the selected adapter */ 00050 for(d=alldevs, i=0; i< inum-1 ;d=d->next, i++);
00051
00052 /* Open the adapter */ 00053 if ( (adhandle= pcap_open_live(d->name, // name of the device 00054 65536, // portion of the packet to capture. 00055 // 65536 grants that the whole packet will be captured on all the MACs. 00056 1, // promiscuous mode 00057 1000, // read timeout 00058 errbuf // error buffer 00059 ) ) == NULL) 00060 { 00061 fprintf(stderr,"\nUnable to open the adapter. %s is not supported by WinPcap\n");
00062 /* Free the device list */ 00063 pcap_freealldevs(alldevs);
00064 return -1;
00065 }
00066
00067 printf("\nlistening on %s...\n", d->description);
00068
00069 /* At this point, we don't need any more the device list. Free it */ 00070 pcap_freealldevs(alldevs);
00071
00072 /* start the capture */ 00073 pcap_loop(adhandle, 0, packet_handler, NULL);
00074
00075 return 0;
00076 }
00077
00078
00079 /* Callback function invoked by libpcap for every incoming packet */ 00080 void packet_handler(u_char *param, const struct pcap_pkthdr *header, const u_char *pkt_data)
00081 {
00082 struct tm *ltime;
00083 char timestr[16];
00084
00085 /* convert the timestamp to readable format */ 00086 ltime=localtime(&header->ts.tv_sec);
00087 strftime( timestr, sizeof timestr, "%H:%M:%S", ltime);
00088
00089 printf("%s,%.6d len:%d\n", timestr, header->ts.tv_usec, header->len);
00090
00091 }
documentation.
Copyright (c)
2002-2003 Politecnico di Torino.
2005 translated by Telebusiness,Inc.
All rights reserved.