So I've been playing around with libpcap lately, and I have a quick question. Here's the code in question:
while( (result = pcap_next_ex(adapterHandle, &header, &packetData)) >= 0)
{
if(result == 0) // Packet was dropped
continue;
ethernet = (struct sniff_ethernet*)packetData;
ip = (struct sniff_ip*)(packetData + SIZE_ETHERNET);
size_ip = IP_HL(ip)*4;
ip_len = ntohs(ip->ip_len);
if(ip->ip_p != IPPROTO_TCP)
continue;
tcp = (struct sniff_tcp*)(packetData + SIZE_ETHERNET + size_ip);
size_tcp = TH_OFF(tcp)*4;
if(size_tcp < 20)
{
cout << "Invalid TCP Header" << endl;
exit(-1);
}
payload = (u_char*)(packetData + SIZE_ETHERNET + size_ip + size_tcp);
size_payload = ip_len - (size_ip + size_tcp);
cout << "************** Output A ******************" << endl;
开发者_如何学Pythoncout << payload << endl;
cout << "*************** Output B *****************" << endl;
for(int i=0; i<size_payload; i++)
cout << payload[i];
}
So in my test I set it up so that I only capture HTTP "GET" requests. Now in my mind the output of Output A and Output B should be the same, printing only the HTTP header. Output B always prints it out correctly, but Output A occasionally has the HTTP header plus about 7 bytes of random text added on to it as well(Like this "ï╤↔N↓ƒ♂").
So the questions are where does that garbled text come from? And what's the difference between just printing the payload directly as in Output A vs looping through it and printing each character as in Output B?
Well, if it's not NUL
-terminated (\0
) it won't know where to stop, so it will print garbage text. You might want to do:
payload[size_payload] = '\0'; /* Before using it. */
精彩评论