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 recv
with the MSG_PEEK
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:
// 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->length) * sizeof(char);
int msglen = sizeof(int) + txtlen;
// Read complete packet.
m = realloc (m, msglen);
read (sock, m, msglen);
m->text[txtlen] = '\0';
// Show result.
printf("%s\n", &m->text);
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?