Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
get offset to user data from tcp header
#1
I searched  and found this link
data from tcp_hdr 

which shows
 
Code:
(char *)((unsigned char *)tcph + (tcph->doff * 4));

Now my questions is, doff is already representing size of tcp-header in 32 bit word form. Then why tcph is added with it   (see above code).

Also why it typecasted in char*  . if we have offset in integer form?
Reply
#2
before we discuss the same let us pull the reference to understand the same:
1. struct tcphdr definition in kernel-source (even user library should be same) here: http://lxr.free-electrons.com/source/inc.../tcp.h#L24

2. TCP Header diagram where the doff field is mentioned: https://nmap.org/book/tcpip-ref.html
-----------
Your question: doff is already representing size of tcp-header in 32 bit word form. Then why tcph is added with it
data = (char *)((int)tcph + (int)(tcph->doff * 4));

It is simple Shyam:
They are doing
(pointer of tcphdr)+(total bytes of tcphdr) ===> give you the first pointer of its payload (or data) pointer

doff tells count of number of octects (since some TCP headers may contain options) so total doff*4 => TCP-Header length

so assume a simple sample code:
char *data=NULL;
struct tcphdr *tcph;
and point tcph = (to some location);

Then set the "data" with data=(char *)((unsigned char *)tcph + (tcph->doff * 4));

Your next question:
Also why it typecasted in char* . if we have offset in integer form?
>> well this is int (or short whatever) => (tcph->doff * 4)
but this is a pointer: (tcph + (tcph->doff * 4))
since all you are doing is pointer+integer => pointer
something like:
int *p;
p=p+10;

so ((unsigned char *)tcph + (tcph->doff * 4)) => is a pointer, but to assign for data they need to do:
data = (char *)((int)tcph + (int)(tcph->doff * 4));

Hope it answers the question Wink
Kiran
Reply
#3
Thanks a lot Sir. I got your point its simple pointer arithmetic.
Smile
Reply
#4
Exactly Smile
This is also the reason I both love and hate pointers in C (and C++).
I hate them, since it makes code less understandable and vulnerable causing bugs or even crashes.
For example even a simple statement like this.
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)