title: TCPDump / libpcap - find memory location of payload data
body: <p>I am trying to view http traffic going to and from my loopback network adapter using libpcap. I just beginning with network programming and completely new to this library. Thanks to an <a href="https://stackoverflow.com/questions/17129532/libpcap-packet-ip-header-length-is-zero-bytes-with-loopback-tcp-requests">answer</a> I received previously I have been successful at detecting the link-layer type on my machine's "lo0" adapter (Mac OSx).</p>
  
  <pre><code>//lookup link-layer header type
  link_layer_type = pcap_datalink(handle);
  if(link_layer_type == DLT_NULL){
      printf("DLT_NULL"); // this true in the case of "lo0"
  }
  </code></pre>
  
  <p>The <a href="http://www.tcpdump.org/pcap.html" rel="nofollow noreferrer">Programming with Pcap</a> guide makes the assumption that each packet will contain an ethernet header. So the logic used to find a packet's payload is as follows:</p>
  
  <pre><code> ethernet = (struct sniff_ethernet*)(packet);
      ip = (struct sniff_ip*)(packet + SIZE_ETHERNET);
      size_ip = IP_HL(ip)*4;
      if (size_ip &lt; 20) {
          printf("   * Invalid IP header length: %u bytes\n", size_ip);
          return;
      }
      tcp = (struct sniff_tcp*)(packet + SIZE_ETHERNET + size_ip);
      size_tcp = TH_OFF(tcp)*4;
      if (size_tcp &lt; 20) {
          printf("   * Invalid TCP header length: %u bytes\n", size_tcp);
          return;
      }
  }
  
  payload = (u_char *)(packet + SIZE_ETHERNET + size_ip + size_tcp);
  </code></pre>
  
  <p>This logic is clearing not going to work when inspecting the contents of packet originating from the loopback interface where an ethernet header does not exists. The <a href="http://www.tcpdump.org/linktypes.html" rel="nofollow noreferrer">Link-Layer Header Types documentation</a> states that a Link-Layer type of "DTL_NULL" contains a 4 byte header which consist of a PF_ value containing the network-layer protocol (I'm guess IPv4 in my case). </p>
  
  <p>Given the above information.. how can I properly locate the packet's payload location?</p>
  
  <p>Any guidance or information would be very appreciated. Thanks!</p>