How to send structure using sendto ()

I created a structure:

struct buffer
{
    string ProjectName ;
    string ProjectID ;
}

buffer buf;
buf.ProjectID = "212";
buf.ProjectName = "MyProj";

Now, to send this structure using the sendto method, I will draw a structure and send it as shown below:

char *sendbuf = (char*)&buf;
sentbytes = sendto(sock,sendbuf,strlen(sendbuf),0,(sockaddr*)&their_addr,sizeof(their_addr));

But while I sketch my Struct ti char*, the actual data loses its values, and during debugging I see that sendbuf contains some other values.

Can someone let me know how I can send the specified structure using sendto.

+2
source share
3 answers

You need to create a structure using POD, the string cannot be used this way. Instead, you need to declare something like

struct buffer
{
  char ProjectName[MAX_LENGTH_PROJECT_NAME+1];
  char ProjectID[MAX_LENGTH_PROJECT_ID+1];
};

EDIT: , , , .

+2

std::string . , , std::string::c_str std::string::size.

+2

marshall/unmarshall . ++ "</lt;/ → " . , , (, , xml,...). Boost .

+1
source

Source: https://habr.com/ru/post/1762434/


All Articles