send(2)
by default returns only when all data was successfully copied to the send buffers.
The possible ways to force it to send less bytes highly depend on the circumstances.
If you
1. can access the socket
2. do not want to alter the behaviour of all calls to send
in your linked binary,
then you could set the socket non-blocking. Then, a call to send
will send as much octects as possible. The amount of octets sent depends mainly on the amount of free memory in the send buffer of the socket you want to send on.
Thus, if you got
uint8_t my_data[NUM_BYTES_TO_SEND] = {0}; /* We don't care what your buffer actually contains in this example ... */
size_t num_bytes = sizeof(my_data);
send(fd, my_data, num_bytes);
and want send
to send less than num_bytes
, you could try to decrease the send buffer of your socket fd
.
Whether this is possible, how to accomplish this might depend on your OS.
Under Linux, you could try to shrink the send buffer by setting the buffer size manually by using setsockopt(2)
via the option SO_SNDBUF
, descibed in the man page `socket(7):
uint8_t my_data[NUM_BYTES_TO_SEND] = {0};
size_t num_bytes = sizeof(my_data);
size_t max_bytes_to_send = num_bytes - 1; /* Force to send at most 1 byte less than in our buffer */
/* Set the socket non-blocking - you should check status afterwards */
int status = fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0) | O_NONBLOCK);
/* reduce the size of the send buffer below the number of bytes you want to send */
setsockopt (fd, SOL_SOCKET, SO_SNDBUF, &max_bytes_to_send, sizeof (size_t));
...
send(fd, my_data, num_bytes);
/* Possibly restore the old socket state */
Possibly you also have to fiddle around with the option SO_SNDBUFFORCE
.
Further info for
Anyhow, the best way to go for you depends on the circumstance.
If you look for a reliable solution to check code you perhaps cannot even access, but link into your project dynamically, you might go with the other approach suggested here: Overshadow the send
symbol in your compiled code .
On the other hand, this will impact all calls to send
in your code (you could, of course bypass this problem e.g. by having your send
replacement depend on some flags you could set).
If you can access the socket fd, and want only specific send
calls to be impacted (as I guess is the case with you, since you talk about unit tests, and checking for sending less bytes than expected in all your tests is probably not what you want?), then going the way to shrink the send buffer could be the way to go.