title: C++ - Constructing a packet with headers and sending it through a UDP socket
body: <p>I am trying to build a packet that will be sent via UDP. However I am not getting the correct data on the receiving side.</p>
  
  <p>In the packet I want to include an IP Header, UDP Header, and the data that needs to be sent. In this case I just want to send the word "Hello" along with random header information.</p>
  
  <pre><code>char *data = "Hello";
  char *packet = (char *)malloc(sizeof(struct iphdr) + sizeof(struct udphdr) + strlen(data));
  struct iphdr *ip = (struct iphdr*) packet;
  struct udphdr *udp = (struct udphdr*) (packet + sizeof(struct iphdr));
  char *send_buff = (char *) (packet + sizeof(struct iphdr) + sizeof(struct udphdr));
  ip-&gt;saddr = inet_addr("1.2.3.4");
  ip-&gt;daddr = inet_addr("5.6.7.8");
  ip-&gt;ttl = 5;
  udp-&gt;source = 5950;
  udp-&gt;dest = 5950;
  udp-&gt;len = sizeof(struct udphdr);
  udp-&gt;check = 0;
  strcpy(send_buff, data);
  
  sendto(sock, packet, (sizeof(struct iphdr) + sizeof(struct udphdr) + strlen(data)), ROUTER_IP);
  </code></pre>
  
  <p>The problem I'm having is that the receiving end just gets random data so I'm assuming the number of bytes is incorrect somewhere.</p>
  
  <p>On the receiving side I have it print out one of the fields of the IP header as a test, but it's not correct.</p>
  
  <pre><code>char recv_buff[1000];
  int recv_bytes = recvfrom(sock, recv_buff, sizeof(recv_buff));
  struct iphdr *ip = (struct iphdr*) recv_buff;
  cout &lt;&lt; static_cast&lt;int16_t&gt;(ip-&gt;ttl) &lt;&lt; endl;
  </code></pre>
  
  <p>Am I putting the packet together wrong or is there a problem on the receiving end?
  I used this example <a href="http://www.winlab.rutgers.edu/~zhibinwu/html/c_prog.htm" rel="nofollow">http://www.winlab.rutgers.edu/~zhibinwu/html/c_prog.htm</a> as a reference for putting together the packet.</p>