You are not logged in.
Pages: 1
Hi all,
I'm hoping someone can help me figure out how to send() a message with a fixed-size (in bytes). So far, I've acquainted myself with sockets well enough to send messages across a socket stream, but now I'd like to send a single 200-byte message with TCP. Since size_t len seems to be relative to the data-type, I'm not sure how I can create a message of fixed length in bytes.
Thanks!
Offline
I'm not really clear about what you're asking... If you're talking about how to send and receive a fixed-sized message over TCP, then you have 2 choices: prefix each message with a fixed-length size header; or, suffix each message with a delimiter character/string... I lean towards choice 1 as the easiest to code for, but choice 2 is more appropriate if you need to be able to manually interact with the program via telnet or something... Just as a simple example:
uint16_t len;
char msg[200];
/* fill "msg" however... */
len = 200;
send (sock, &len, sizeof (len), 0);
send (sock, msg, len, 0);
/* ... in the receiver... */
uint16_t len;
char *msg;
recv (sock, &len, sizeof (len), 0);
msg = malloc (len);
recv (sock, msg, len, 0);
Note: the above code is just a bare-bones example, and shouldn't be used as-is... You need to check the return values of send()/recv(), because not only can there be errors, but they can both return short writes/reads, requiring you to loop until you send/receive everything... (You might be able to use MSG_WAITALL as an alternative to doing your own looping...) Also, for real uses, you probably want to use htons() on the sent length header, and ntohs() on the received one, so that if the sender and receiver are on different architectures, things will still work...
This also assumes you need to send different messages of different sizes... If your program is only ever always going to be sending the same exact fixed-sized message, then you can just send it without any header and have your receiver already know exactly how much to always receive...
Offline
uint16_t len;
char msg[200];
/* fill "msg" however... */
len = 200;
send (sock, &len, sizeof (len), 0);
send (sock, msg, len, 0);
/* ... in the receiver... */
uint16_t len;
char *msg;
recv (sock, &len, sizeof (len), 0);
msg = malloc (len);
recv (sock, msg, len, 0);
Offline
Pages: 1