0

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?

1 Answers1

2
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;
cnicutar
  • 178,505
  • 25
  • 365
  • 392
  • Well,I tried your answear.But it don't work.The `th` still be `0x603ebe`. `0x603ebe` minus `0x603cde` is `0x1e0` which equals to 480.And the `sizeof ip_header` is 20 bytes. So `20 * sizeof ip_header`should be 400. – user3589797 May 08 '14 at 12:53
  • @user3589797 You must be doing something wrong that is not obvious from what you have posted. – cnicutar May 08 '14 at 13:04
  • I made a mistake when I try your answear. Your answear is right.Thank you very much. – user3589797 May 08 '14 at 13:15