Home > Enterprise >  Recv() returns the correct lenght but don't copy the message
Recv() returns the correct lenght but don't copy the message

Time:10-31

I have the next code:

while(1) {
int length=sizeof(client);
connSock=accept(readSock, (struct sockaddr*) &client,&length);
if(!fork()) 
    {
    close(readSock);
    char receiveBuff[1000],sendBuff[1000];
    int status;
    int size_buf;
    do {
        status=recv(connSock, receiveBuff, 1000,0);
        printf("%d status \n",status);
        printf("%s recv buff\n", receiveBuff);
        memcpy(sendBuff,receiveBuff,sizeof(receiveBuff));
        send(connSock, &sendBuff, sizeof(sendBuff), 0);

    }while (status!=0);
    close(connSock);
    exit(0);
}
close(connSock);

}

I am trying to send a message "Test" and the recv() function returns 4 (the correct lenght) but when i try to print the receiveBuffer it doesnt work. This is the output:

4 status 
h: recv buff

This is the code from clinet side:

   void Client_Connector::Start_Connection()
{
    this->sock=socket(AF_INET,SOCK_STREAM,0);
    bzero(&this->server,sizeof(server));
    this->server.sin_family=AF_INET;
    inet_pton(AF_INET,"127.0.0.1", &this->server.sin_addr);
    server.sin_port=htons(2500);
    int status=connect(sock,(struct sockaddr*) &server, sizeof(server));
    if (status==0)
        cout<<"Sunteti conectat! \n";
    else
        Eroare("Eroare de conexiune! Conexiunea nu s-a putut realiza.");

}

void Client_Connector::send_Buffer(char* sendMessage)
{
    int i;
    i=send(sock, &sendMessage,strlen(sendMessage) 1,0);
    cout<<i<<endl;
}

And just call the function:

connecter.Start_Connection();
    string sendmsg("Test");
    sendmsg ="\0";
    connecter.send_Buffer((char*)sendmsg.c_str());

CodePudding user response:

The problem is that you don't actually send the string, you send the pointer to the string:

i=send(sock, &sendMessage,strlen(sendMessage),0);

Here &sendMessage will be a pointer to the variable sendMessage, not a pointer to the first character of the string.

Simple solution:

i = send(sock, sendMessage, strlen(sendMessage)   1, 0);

That will send the actual string contents, including the terminating null character.


I also recommend you take a couple of steps back, and refresh your knowledge of arrays and pointers and the associated operators.

  • Related