UNIX Socket FAQ

A forum for questions and answers about network programming on Linux and all other Unix-like systems

You are not logged in.

#1 2019-05-22 03:47 PM

MatthewD01
Member
Registered: 2019-05-21
Posts: 2

send() message size

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

#2 2019-05-22 05:35 PM

RobSeace
Administrator
From: Boston, MA
Registered: 2002-06-12
Posts: 3,847
Website

Re: send() message size

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

#3 2019-05-28 05:55 PM

MatthewD01
Member
Registered: 2019-05-21
Posts: 2

Re: send() message size

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

Board footer

Powered by FluxBB