readfile.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. #include <stdio.h>
  2. #include <pcap.h>
  3. #define LINE_LEN 16
  4. #ifdef _WIN32
  5. #include <tchar.h>
  6. BOOL LoadNpcapDlls()
  7. {
  8. _TCHAR npcap_dir[512];
  9. UINT len;
  10. len = GetSystemDirectory(npcap_dir, 480);
  11. if (!len) {
  12. fprintf(stderr, "Error in GetSystemDirectory: %x", GetLastError());
  13. return FALSE;
  14. }
  15. _tcscat_s(npcap_dir, 512, _T("\\Npcap"));
  16. if (SetDllDirectory(npcap_dir) == 0) {
  17. fprintf(stderr, "Error in SetDllDirectory: %x", GetLastError());
  18. return FALSE;
  19. }
  20. return TRUE;
  21. }
  22. #endif
  23. void dispatcher_handler(u_char *, const struct pcap_pkthdr *, const u_char *);
  24. int main(int argc, char **argv)
  25. {
  26. pcap_t *fp;
  27. char errbuf[PCAP_ERRBUF_SIZE];
  28. #ifdef _WIN32
  29. /* Load Npcap and its functions. */
  30. if (!LoadNpcapDlls())
  31. {
  32. fprintf(stderr, "Couldn't load Npcap\n");
  33. exit(1);
  34. }
  35. #endif
  36. if(argc != 2)
  37. {
  38. printf("usage: %s filename", argv[0]);
  39. return -1;
  40. }
  41. /* Open the capture file */
  42. if ((fp = pcap_open_offline(argv[1], // name of the device
  43. errbuf // error buffer
  44. )) == NULL)
  45. {
  46. fprintf(stderr,"\nUnable to open the file %s.\n", argv[1]);
  47. return -1;
  48. }
  49. /* read and dispatch packets until EOF is reached */
  50. pcap_loop(fp, 0, dispatcher_handler, NULL);
  51. pcap_close(fp);
  52. return 0;
  53. }
  54. void dispatcher_handler(u_char *temp1,
  55. const struct pcap_pkthdr *header,
  56. const u_char *pkt_data)
  57. {
  58. u_int i=0;
  59. /*
  60. * unused variable
  61. */
  62. (VOID*)temp1;
  63. /* print pkt timestamp and pkt len */
  64. printf("%ld:%ld (%ld)\n", header->ts.tv_sec, header->ts.tv_usec, header->len);
  65. /* Print the packet */
  66. for (i=1; (i < header->caplen + 1 ) ; i++)
  67. {
  68. printf("%.2x ", pkt_data[i-1]);
  69. if ( (i % LINE_LEN) == 0) printf("\n");
  70. }
  71. printf("\n\n");
  72. }