Sunday, March 29, 2009

Socket Programming: Dynamic sized data

I have been posted on linux-c-programming@vger.kernel.org regarding receiving dynamic size data using TCP/IP socket, and now resolved:

struct foo {
  char *name;
  unsigned int id;
};

int ret, len;
struct foo *bar = malloc (sizeof(struct foo));
/* fill bar */
len = strlen (name);
send (s, &len, sizeof(len), 0);
send (s, bar->name, len, 0);
send (s, &bar->id, sizeof(bar->id), 0);

And for the receiver:

recv (s, &len, sizeof(len), 0);
/* allocate bar->name for len bytes */
recv (s, bar->name, len, 0);

Notice there are no error checking and network byte ordering here.