readfile_ex.c 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. int main(int argc, char **argv)
  24. {
  25. pcap_t *fp;
  26. char errbuf[PCAP_ERRBUF_SIZE];
  27. struct pcap_pkthdr *header;
  28. const u_char *pkt_data;
  29. u_int i=0;
  30. int res;
  31. #ifdef _WIN32
  32. /* Load Npcap and its functions. */
  33. if (!LoadNpcapDlls())
  34. {
  35. fprintf(stderr, "Couldn't load Npcap\n");
  36. exit(1);
  37. }
  38. #endif
  39. if(argc != 2)
  40. {
  41. printf("usage: %s filename", argv[0]);
  42. return -1;
  43. }
  44. /* Open the capture file */
  45. if ((fp = pcap_open_offline(argv[1], // name of the device
  46. errbuf // error buffer
  47. )) == NULL)
  48. {
  49. fprintf(stderr,"\nUnable to open the file %s.\n", argv[1]);
  50. return -1;
  51. }
  52. /* Retrieve the packets from the file */
  53. while((res = pcap_next_ex(fp, &header, &pkt_data)) >= 0)
  54. {
  55. /* print pkt timestamp and pkt len */
  56. printf("%ld:%ld (%ld)\n", header->ts.tv_sec, header->ts.tv_usec, header->len);
  57. /* Print the packet */
  58. for (i=1; (i < header->caplen + 1 ) ; i++)
  59. {
  60. printf("%.2x ", pkt_data[i-1]);
  61. if ( (i % LINE_LEN) == 0) printf("\n");
  62. }
  63. printf("\n\n");
  64. }
  65. if (res == -1)
  66. {
  67. printf("Error reading the packets: %s\n", pcap_geterr(fp));
  68. }
  69. pcap_close(fp);
  70. return 0;
  71. }