Last Updated: February 25, 2016
·
3.265K
· zedtux

C - Calculate TCP Socket data length

For a private project I had to calculate the sequences of packets.

To do that I must found the size of the data of TCP packets.

To calculate it, after having allocated the iphdr and tcphdr structures...

struct tcphdr * tcp_header = NULL;
struct iphdr * ip_header = ip_hdr(skb);

switch(ip_header->protocol)
{
    case IPPROTO_TCP:
        tcp_header = udp_hdr(skb);
        ...
    break;
    ...
}

Then you have to do the following:

int tcpdatalen = ntohs(ip_header->tot_len) - (tcp_header->doff * 4) - (ip_header->ihl * 4);

Then the tcpdatalen variable contains the length that could be 0 for example if the packet is a SYN packet.