title: When to use ntohs function in net programming?
body: <p>I am learning net programming using WinPcap. Here is the snippet:</p>
  
  <pre><code>int ip_hlen = (ih-&gt;ver_ihl &amp; 0xf) * 4; /* get ip header length */
  tcp_header *th = (tcp_header *) ((u_char*)ih + ip_len);
  int tcp_hlen = (ntohs(th-&gt;th_len_resv_code) &amp; 0xf000) &gt;&gt; 12)*4; /* get tcp header length */
  </code></pre>
  
  <p>The problem is why <code>ntohs</code> is only used when getting  <code>tcp_hlen</code> not <code>ip_hlen</code>.<br>
  Indeed, <code>ntohs</code> only taks in <code>u_short</code> as parameter explains a little. <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms740075%28v=vs.85%29.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/windows/desktop/ms740075%28v=vs.85%29.aspx</a></p>
  
  <p><strong>I am still puzzled about when using ntohs when not.</strong></p>
  
  <p>Here is the struct of IP and TCP packet definition:</p>
  
  <pre><code>/* ipv4 header */
  typedef struct ip_header {
      u_char ver_ihl;         /* version and ip header length */
      u_char tos;             /* type of service */
      u_short tlen;           /* total length */
      u_short identification; /* identification */
      u_short flags_fo;       // flags and fragment offset
      u_char ttl;             /* time to live */
      u_char proto;           /* protocol */
      u_short crc;            /* header checksum */
      ip_address saddr;       /* source address */
      ip_address daddr;       /* destination address */
      u_int op_pad;           /* option and padding */
  }ip_header;
  
  /* tcp header */
  typedef struct tcp_header {
      u_short th_sport;         /* source port */
      u_short th_dport;         /* destination port */
      u_int th_seq;             /* sequence number */
      u_int th_ack;             /* acknowledgement number */
      u_short th_len_resv_code; /* datagram length and reserved code */
      u_short th_window;        /* window */
      u_short th_sum;           /* checksum */
      u_short th_urp;           /* urgent pointer */
  }tcp_header;
  </code></pre>