作業例として、次のコードを扱うことができます。
#include <sys/socket.h>
#define size_t SOCKET
int receive_socket_data(SOCKET sock,//socket representing remote connection
unsigned long& version_number,//validPtr->version #
unsigned long& message_size,//validPtr->sizeof packet
char*& buf // where to copy data from packet
)
{
int nlen = 0;
buf = NULL;
// Receive version_number from the packet
nlen = recv(sock, (char*) &version_number, sizeof(version_number), 0);
if (nlen == 0 || nlen == -1) return ERROR_RECEIVING;
version_number = ntohl(version_number);
// Receive message_size from the entire packet
// (ulong + ulong + sizeof data)
nlen = recv(sock, (char*) &message_size, sizeof(message_size), 0);
if (nlen == 0 || nlen == -1) return ERROR_RECEIVING;
message_size = ntohl(message_size);
// Allocate a buffer to copy the data part of the packet
buf = new char[message_size + 1 - 2 * sizeof(unsigned long)];
buf[message_size - 2 * sizeof(unsigned long)] = '\0';
// Copy the data part from the packet to the buffer
if (recv(sock, (char*) buf, message_size-2*sizeof(unsigned long), 0) == -1)
return ERROR_RECEIVING;
return SUCCESS_RECEIVING;
}
たとえば、私が念頭に置いているのは、演算子newによってエラーがスローされる可能性です。
配列のインデックス計算も問題を引き起こす可能性があるかどうかはわかりません。