I tried to code to give the statistics of a saved .pcap
file in C++ using the npcap library.
My IPv4 count is correct and matches Wireshark's IPv4 count, but my TCP and UDP don't match with Wireshark's statistics.
Output of my code:
Output of the same .pcap
file in Wireshark:
Here is my code:
void PcapSolutionFast::generateStats() {
ipv4_header* ip4;
ethernet_header* ethernet; /* The ethernet header */
u_short eth_type;
while (pcap_next_ex(pcap, &header, &data) >= 0) {
//count every packets
ethernet = (ethernet_header*)(data);
eth_type = ntohs(ethernet->ether_type);
if (eth_type == 0x0800) {
ip4 = (ipv4_header*)(data + 14); // 14 is header length of ethernet
if (ip4->proto == 6 /* tcp protocol number */) {
tcpCount++;
}
else if (ip4->proto == 17) {//udp protocol number
udpCount++;
}
ipv4Count++; //count total ipv4 packets
}
++packetCount; //count all the packets
}
These are the data structure used:
#define ETHER_ADDR_LEN 6 //mac address length is 6
#define ETHER_HEADER_LEN 14 //header length of ethernet is fixed i.e 14
/* Ethernet or MAC addresses are 6 bytes */
/* Ethernet header */
struct ethernet_header {
u_char ether_dhost[ETHER_ADDR_LEN]; /* Destination Mac address */
u_char ether_shost[ETHER_ADDR_LEN]; /* Source Mac address */
u_short ether_type; /* IP/ ARP/ RARP/ etc */
};
//divided each ip_address octet into 4 u_char
typedef struct ip_address {
u_char byte1;
u_char byte2;
u_char byte3;
u_char byte4;
}ip_address;
//ipv4 ip header
typedef struct ipv4_header {
u_char ver_ihl; // Version (4 bits) + Internet header length (4 bits)
u_char tos; // Type of service
u_short tlen; // Total length
u_short identification; // Identification
u_short flags_fo; // Flags (3 bits) + Fragment offset (13 bits)
u_char ttl; // Time to live
u_char proto; // Protocol
u_short crc; // Header checksum
ip_address saddr; // Source address
ip_address daddr; // Destination address
u_int op_pad; // Option + Padding
}ipv4_header;
/* IPv6 header */
typedef struct ipv6_header
{
unsigned int
version : 4,
traffic_class : 8,
flow_label : 20;
uint16_t length;
uint8_t next_header;
uint8_t hop_limit;
struct in6_addr saddr;
struct in6_addr daddr;
} ipv6_header;
Why is it that my TCP and UDP counts are not the same as Wireshark's statistics?