TCP send struct not working Unhandled exception

So I want to send a char and a const char from the tcp client to the server, but the code I have below

This is the sender

struct packet {
    char caseRadio;//1byte
    const char* path;//4byte
    
};

packet* clientPacket = new packet;

string a = "C:\\Users\\Desktop\\Project phoneedge\\ForJen";
clientPacket->caseRadio = '1';
clientPacket->path = a.c_str();

int iSend1 = send(TCPClientSocket, (char*)clientPacket, sizeof(packet), 0);

This is the reciever

struct packet {
    char caseRadio;//1byte
    const char* path;//4byte
};

packet* clientPacket = new packet;

int iRecv = recv(sAccecpSocket, (char*)clientPacket, sizeof(packet),0);
cout << clientPacket->caseRadio << endl;
cout << clientPacket->path << endl;

I only receive the caseRadio's 1 the path throws a Unhandled exception at 0x7A8308F0 (ucrtbased.dll) in Barebonesserver.exe:

At some point the path printed out something like this \source\repos\Barebonesserver\Debug\Barebonesserver.exe (this is a part of the project folder path, just how?)


Solution 1:

Send a const char * over TCP does not make sense. A const char * is only the address of a string in the memory of the sender process. It cannot magically point to something interesting in the reader process. Furthermore, sending a struct over the network is not reliable, because different compilation options could lead to different paddings in the structures.

You need to serialize your data. A common way would be to send:

  • a single char for caseRadio
  • a 16 bit integer in network order for the size of the character string
  • the bytes of the character string

Sender side (tests of iSend1 omitted form brievety):

...
string a = "C:\\Users\\Desktop\\Project phoneedge\\ForJen";

int iSend1 = send(TCPClientSocket, '1', 1, 0);;
int iSend1 = send(TCPClientSocket, htons(a.size()), 2, 0);
int iSend1 = send(TCPClientSocket, a.c_str(), a.size(), 0);

Reciever side (test omitted ibidem):

char caseRadio
uint16_t size;
char *data;
int iRecv = recv(sAccecpSocket, &caseRadio, 1, 0);
int iRecv = recv(sAccecpSocket, &size, 2, 0);
size = ntohs(size);   // revert to host order...
data = new char[size];
int iRecv = recv(sAccecpSocket, data, size, 0);
string a{data, size};
delete[] data;