basic_dump_ex.c 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. #include "pcap.h"
  2. #include <time.h>
  3. int main()
  4. {
  5. pcap_if_t *alldevs;
  6. pcap_if_t *d;
  7. int inum;
  8. int i=0;
  9. pcap_t *adhandle;
  10. int res;
  11. char errbuf[PCAP_ERRBUF_SIZE];
  12. struct tm ltime;
  13. char timestr[16];
  14. struct pcap_pkthdr *header;
  15. const u_char *pkt_data;
  16. time_t local_tv_sec;
  17. /* Retrieve the device list on the local machine */
  18. if (pcap_findalldevs_ex(PCAP_SRC_IF_STRING, NULL, &alldevs, errbuf) == -1)
  19. {
  20. fprintf(stderr,"Error in pcap_findalldevs: %s\n", errbuf);
  21. exit(1);
  22. }
  23. /* Print the list */
  24. for(d=alldevs; d; d=d->next)
  25. {
  26. printf("%d. %s", ++i, d->name);
  27. if (d->description)
  28. printf(" (%s)\n", d->description);
  29. else
  30. printf(" (No description available)\n");
  31. }
  32. if(i==0)
  33. {
  34. printf("\nNo interfaces found! Make sure Npcap is installed.\n");
  35. return -1;
  36. }
  37. printf("Enter the interface number (1-%d):",i);
  38. scanf_s("%d", &inum);
  39. if(inum < 1 || inum > i)
  40. {
  41. printf("\nInterface number out of range.\n");
  42. /* Free the device list */
  43. pcap_freealldevs(alldevs);
  44. return -1;
  45. }
  46. /* Jump to the selected adapter */
  47. for(d=alldevs, i=0; i< inum-1 ;d=d->next, i++);
  48. /* Open the device */
  49. if ( (adhandle= pcap_open(d->name, // name of the device
  50. 65536, // portion of the packet to capture.
  51. // 65536 guarantees that the whole packet will be captured on all the link layers
  52. PCAP_OPENFLAG_PROMISCUOUS, // promiscuous mode
  53. 1000, // read timeout
  54. NULL, // authentication on the remote machine
  55. errbuf // error buffer
  56. ) ) == NULL)
  57. {
  58. fprintf(stderr,"\nUnable to open the adapter. %s is not supported by Npcap\n", d->name);
  59. /* Free the device list */
  60. pcap_freealldevs(alldevs);
  61. return -1;
  62. }
  63. printf("\nlistening on %s...\n", d->description);
  64. /* At this point, we don't need any more the device list. Free it */
  65. pcap_freealldevs(alldevs);
  66. /* Retrieve the packets */
  67. while((res = pcap_next_ex( adhandle, &header, &pkt_data)) >= 0){
  68. if(res == 0)
  69. /* Timeout elapsed */
  70. continue;
  71. /* convert the timestamp to readable format */
  72. local_tv_sec = header->ts.tv_sec;
  73. localtime_s(&ltime, &local_tv_sec);
  74. strftime( timestr, sizeof timestr, "%H:%M:%S", &ltime);
  75. printf("%s,%.6d len:%d\n", timestr, header->ts.tv_usec, header->len);
  76. }
  77. if(res == -1){
  78. printf("Error reading the packets: %s\n", pcap_geterr(adhandle));
  79. return -1;
  80. }
  81. return 0;
  82. }