title: Is it possible to peek at a datagram packet in higher-level languages?
body: <p>I am currently trying to port a C program that deals with datagram (UDP) packets to some higher-level language. As the packets can be of variable size, they start with an integer stating their size. In c, I call <code>recv</code> with the <code>MSG_PEEK</code> flag to first receive this value only, then allocate a fitting buffer and read the rest of the packet. The code (simplified) goes like this:</p>
  <pre><code>// Simplified message format.
  struct message {
      int length;
      char[] text;
  }
  struct message *m = malloc (sizeof(int));
  
  // Read out in just length.
  recv (sock, m, sizeof(int), MSG_WAITALL | MSG_PEEK);
  int txtlen = ntohl (m-&gt;length) * sizeof(char);
  int msglen = sizeof(int) + txtlen;
  
  // Read complete packet.
  m = realloc (m, msglen);
  read (sock, m, msglen);
  m-&gt;text[txtlen] = '\0';
  
  // Show result.
  printf(&quot;%s\n&quot;, &amp;m-&gt;text);
  </code></pre>
  <p>I want to avoid the seemingly common practice to allocate an enormous buffer and hope that no bigger packets will arrive. So is something like peeking at the datagram or determining its complete length beforehand possible in higher-level languages like python or java?</p>