title: C - Linux - kernel module - TCP header
body: <p>I'm trying to create linux kernel module, that will inspect incoming packets. At the moment, I'm in process of extracting TCP header of packet and reading source and destination port -> However I'm getting incorrect values. I have hook function:</p>
  
  <pre class="lang-c prettyprint-override"><code>unsigned int hook_func(unsigned int hooknum, struct sk_buff *skb, 
                         const struct net_device *in, 
                         const struct net_device *out, 
                         int (*okfn)(struct sk_buff *)) 
  {
      struct iphdr *ipp = (struct iphdr *)skb_network_header(skb);
      struct tcphdr *hdr;
      /* Using this to filter data from another machine */
      unsigned long ok_ip = 2396891328;
  
      /* Some problem, empty network packet. Stop it now. */
      if (!skb)
          return NF_ACCEPT;
  
      /* Just to track only packets coming from 1 IP */
      if (ipp-&gt;saddr != ok_ip)
          return NF_ACCEPT;
  
      /* Incomming packet is TCP */
      if (ipp-&gt;protocol == IPPROTO_TCP) {
          hdr = (struct tcphdr *) skb_transport_header(skb);
          printk(" TCP ports: source: %d, dest: %d .\n", ntohs(hdr-&gt;source), 
                                                         ntohs(hdr-&gt;dest));
      }
  }
  </code></pre>
  
  <p>Now, when I try to telnet port <strong>21</strong>(not listening there I get): </p>
  
  <pre><code>[ 4252.961912]  TCP ports: source: 17664, dest: 52 .
  [ 4253.453978]  TCP ports: source: 17664, dest: 52 .
  [ 4253.953204]  TCP ports: source: 17664, dest: 48 .
  </code></pre>
  
  <p>And when I telnet port <strong>22</strong> - SSH deamon listening there:</p>
  
  <pre><code>[ 4299.239940]  TCP ports: source: 17664, dest: 52 .
  [ 4299.240527]  TCP ports: source: 17664, dest: 40 .
  [ 4299.552566]  TCP ports: source: 17664, dest: 40 .
  </code></pre>
  
  <p>As visible from output I'm getting very weird results, anyone has idea where problem is coming from? when I compile module I have no errors / warnings. Version of kernel(headers): 3.7.10 . Not using SELinux or similar.</p>