[oclug] time for my weekly dumb question -> C and memory

David F. Skoll dfs at roaringpenguin.com
Sun Apr 1 22:32:23 EDT 2001


On Sun, 1 Apr 2001, Greg Sarsons wrote:

> Okay just noticed that.  But what if you have fields that you don't know the
> size of until you are building the messages?  How does one get around that
> problem?

You can't use a C structure in that case.  You have to just declare an array
of char and fill it in "by hand", something like this:

/* Assume URL is in "url" and length is "len" */
/* Assume scope data is in "scope_data" and length is "scope_len" */

unsigned char buf[MAX_MSG_LEN];

buf[0] = (len >> 8) & 0xFF;
buf[1] = len & 0xFF;
memcpy(&buf[2], url, len);
buf[2+len] = (scope_len >> 8) & 0xFF;
buf[2+len+1] = scope_len & 0xFF;
memcpy(&buf[2+len+2], scope_data, scope_len);

Note that the lengths are explicitly transmitted in big-endian order
(most significant byte first.)  This is the standard "network byte
order".  You should never use native multibyte types in network
packets, because Intels and Sparcs will not understand one another.

For more info about network programming, you should read "UNIX Network
Programming: Volume 1: Sockets and XTI" by W. Richard Stevens.  (ISBN
0-13-490012-X).  His other book, "Advanced Programming in the UNIX
Environment" is also worth its weight in gold.

--
David.




More information about the OCLUG mailing list