Reading Packet Data With libpcap
Question
I'm working with pcap to monitor http requests and responses. I've setup pcap_loop and I'm getting packets in my callback function but I don't know how to read packets content. this is my callback function:
void got_packet(u_char *args, const struct pcap_pkthdr *header, const u_char *packet)
{
printf("%s\n", packet);
}
The output always looks likes series of a backslashe and three numbers after it
\200\205\300
I was wondering how can I make the content readable so I can find and process http request and responses?
UPDATE:
My goal is to read HTTP requests and responses is there any proper and neat way to do this?
Solution
This is because the output is raw binary data, not an ascii string, so printf outputs it only until the first 0 byte. To print all readable stuff in the packet, use something like:
for (int i = 0; i < header->caplen; ++i) {
if (isascii(packet[i])) {
putchar(packet[i]);
} else {
putchar('.');
}
OTHER TIPS
Libpcap is going to give you a raw packet, including all headers. You'll need to extract out the data you need from it, I suggest by casting it to standard structs that represent the packet. Something like,
/* Start with the ether header */
ethernet = (struct ether_header *) packet;
/* Do a couple of checks to see what packet type we have */
if (ntohs (ethernet->ether_type) == ETHERTYPE_IP)
{
// Cast it to an IP packet struct
ip_hdr = (struct ip*)(packet + sizeof(struct ether_header));
//If TCP...
if(ip_hdr->ip_p == 6)
{
packet_info.tcp_hdr = *(struct tcphdr*)((char*)ip_hdr + sizeof(struct ip));
// Work on extracting the actual data for HTTP stuff over here