readfile_ex.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. #include <stdio.h>
  2. #include <pcap.h>
  3. #include "misc.h"
  4. #define LINE_LEN 16
  5. int main(int argc, char **argv)
  6. {
  7. pcap_t *fp;
  8. char errbuf[PCAP_ERRBUF_SIZE];
  9. char source[PCAP_BUF_SIZE];
  10. struct pcap_pkthdr *header;
  11. const u_char *pkt_data;
  12. u_int i=0;
  13. int res;
  14. /* Load Npcap and its functions. */
  15. if (!LoadNpcapDlls())
  16. {
  17. fprintf(stderr, "Couldn't load Npcap\n");
  18. exit(1);
  19. }
  20. if(argc != 2)
  21. {
  22. printf("usage: %s filename", argv[0]);
  23. return -1;
  24. }
  25. /* Create the source string according to the new WinPcap syntax */
  26. if ( pcap_createsrcstr( source, // variable that will keep the source string
  27. PCAP_SRC_FILE, // we want to open a file
  28. NULL, // remote host
  29. NULL, // port on the remote host
  30. argv[1], // name of the file we want to open
  31. errbuf // error buffer
  32. ) != 0)
  33. {
  34. fprintf(stderr,"\nError creating a source string\n");
  35. return -1;
  36. }
  37. /* Open the capture file */
  38. if ( (fp= pcap_open(source, // name of the device
  39. 65536, // portion of the packet to capture
  40. // 65536 guarantees that the whole packet will be captured on all the link layers
  41. PCAP_OPENFLAG_PROMISCUOUS, // promiscuous mode
  42. 1000, // read timeout
  43. NULL, // authentication on the remote machine
  44. errbuf // error buffer
  45. ) ) == NULL)
  46. {
  47. fprintf(stderr,"\nUnable to open the file %s.\n", source);
  48. return -1;
  49. }
  50. /* Retrieve the packets from the file */
  51. while((res = pcap_next_ex( fp, &header, &pkt_data)) >= 0)
  52. {
  53. /* print pkt timestamp and pkt len */
  54. printf("%ld:%ld (%ld)\n", header->ts.tv_sec, header->ts.tv_usec, header->len);
  55. /* Print the packet */
  56. for (i=1; (i < header->caplen + 1 ) ; i++)
  57. {
  58. printf("%.2x ", pkt_data[i-1]);
  59. if ( (i % LINE_LEN) == 0) printf("\n");
  60. }
  61. printf("\n\n");
  62. }
  63. if (res == -1)
  64. {
  65. printf("Error reading the packets: %s\n", pcap_geterr(fp));
  66. }
  67. return 0;
  68. }