I have a piece of code to send and receive buffers. Is this the right way to do it? And am I guaranteed that the full buffer will be sent and received?
receiving function:
#include <stdio.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <direct.h>
#include <string.h>
#include <stdint.h>
static inline uint32_t ntohl_ch(char const* a)
{
uint32_t x; memcpy(&x, a, sizeof(x));
return ntohl(x);
}
char* recvStrBuffer(SOCKET s)
{
int totalReceived = 0;
int received = 0;
// recv buffer size
char b[sizeof(uint32_t)];
int r = recv(s, b, sizeof(uint32_t), 0);
if (r == SOCKET_ERROR)
{
printf("error recv\n");
return NULL;
}
uint32_t bufferSize = ntohl_ch(&b[0]);
//printf("bufferSize: %d\n", bufferSize);
char* buff = (char*)malloc(sizeof(char) * bufferSize);
while (totalReceived < bufferSize)
{
received = recv(s, buff + totalReceived, bufferSize - totalReceived, 0);
if (received == SOCKET_ERROR)
{
printf("error receiving buffer %d\n", WSAGetLastError());
return NULL;
}
totalReceived += received;
//printf("received: %d\n", received);
//printf("totalReceived: %d\n", totalReceived);
}
//printf("%s", buff);
return buff;
}
sending function:
#include <stdio.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <direct.h>
#include <string.h>
#include <stdint.h>
int sendStrBuffer(SOCKET s, char* buffer)
{
// send buffer size
int bufferSize = strlen(buffer);
//printf("bufferSize: %d\n", bufferSize);
uint32_t num = htonl(bufferSize);
char* converted_num = (char*)#
int res = send(s, converted_num, sizeof(uint32_t), 0);
if (res == SOCKET_ERROR)
{
printf("error send\n");
return SOCKET_ERROR;
}
int totalSent = 0;
int sent = 0;
while (totalSent < bufferSize)
{
sent = send(s, buffer + totalSent, bufferSize - totalSent, 0);
if (sent == SOCKET_ERROR)
{
printf("error sending buffer\n");
return SOCKET_ERROR;
}
totalSent += sent;
//printf("sent: %d\n", sent);
//printf("totalSent: %d\n", totalSent);
}
}
And then in main (receiving part):
char* buffer;
buffer = recvStrBuffer(socket);
if (buffer == NULL) { printf("error %d\n", WSAGetLastError()); }
printf("%s", buffer);
free(buffer);
Main (sending part):
int r = sendStrBuffer(socket, totalBuffer);
if (r == SOCKET_ERROR) { printf("error %d\n", WSAGetLastError()); }