Question

I used libpcap to capture network packet.My code was

adhandle = pcap_open_live(wlan0,65536, PCAP_OPENFLAG_PROMISCUOUS, 1000,errbuf);/*open interface*/ pcap_next_ex(adhandle, &pheader, &pkt_data);/*capture packet*/ ip_header* ih = (ip_header*)(pkt_data+14); tcp_header* th = (tcp_header*)(ih+20);

In above code, pkt_data point to ether header. And I wanted ih point to ip header and th point to tcp header.

Well,I used gdb to debug. I printed these three pointers. Pkt_data point to 0x603cd0. Ih point to 0x603cde.Ih point to right place. Because ih minus pkt_data is 0xe which equal to 14.

But th point to 0x603ebe.Why th point to 0x603ebe?I think th should point to 0x603cf2.For 0x603cf2 is equal to ih plus 20 ?

If I use tcp_header* th = (tcp_header*)(pkt_data+34);.The th will be 0x603cf2 which is right place.Why use pkt_data+34 will work. Butih+20 don't work.

I am very confused about it. Can you help me?

Was it helpful?

Solution

ip_header* ih = (ip_header*)(pkt_data+14);
tcp_header* th = (tcp_header*)(ih+20);

That's how pointer arithmetic works in C: the address is increased such that th points 20 ip_header worth of data away from where you started. Which means the address is increased with 20 * sizeof ip_header.

Instead of that, you want to jump 20 bytes which you can do using:

tcp_header* th = (char *)ih + 20;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top