send() function returns more bytes that it was req

2019-03-04 11:01发布

问题:

I am doing a socket program and, after my server is connected with the device, I am trying to send a message to him. But the send() function returns a number of bytes greater than the number of bytes that is stored on my array. And the message is not being sent.

Here is my code:

StartSendingMessages()
{
    int retorno;
    CString TextRetorno;

    HEX_bufferMessage = new CHAR[7]; // there are seven bytes

    // specifies the state
    HEX_bufferMessage[0] = 0xF0;
    HEX_bufferMessage[1] = 0x15;
    HEX_bufferMessage[2] = 0x31;
    HEX_bufferMessage[3] = 0x04;
    HEX_bufferMessage[4] = 0x02; // green
    HEX_bufferMessage[5] = 0x0E; // C1
    HEX_bufferMessage[6] = 0xF7;

    retorno = send(sckSloMo, HEX_bufferMessage, sizeof(HEX_bufferMessage), 0); 

    TextRetorno.Format("%d", retorno); // retorno = 8
    AfxMessageBox("Bytes enviados: " + TextRetorno);

    if (retorno == SOCKET_ERROR)
    {
        AfxMessageBox("Error Send!!");
        return;
    }
    else if(retorno != 0)
    {
        AfxMessageBox("Send() OK !!");
    }
}

Anyone knows why is this happening??

回答1:

You did not mean sizeof(HEX_bufferMessage). The type of HEX_bufferMessage is [presumably] char*, and the size of a char* is 8 bytes on your [64-bit] system.

Pass the number 7 instead, preferably using a constant, and get rid of that dynamic allocation if the value 7 really is fixed.

const int BUF_SIZE = 7;
char HEX_bufferMessage[BUF_SIZE];

// ...

retorno = send(sckSloMo, &HEX_bufferMessage[0], BUF_SIZE, 0); 


回答2:

The type of HEX_bufferMessage is pointer to CHAR. You are using sizeof( HEX_bufferMessage ) that is equal to 8 in your paltform.



回答3:

Assuming you've got

TYPE* myPointer;

then sizeof(myPointer) will give you the size of the pointer (i.e. 4 bytes on a 32 bit system, 8 on a 64 bit system), not the size of the array.

You want to do

const int bufferSize = 7;
HEX_bufferMessage = new CHAR[bufferSize]; 

...

retorno = send(sckSloMo, HEX_bufferMessage, sizeof(CHAR) * bufferSize, 0); 


回答4:

It seems you assume that sizeof(HEX_buffer_message) yields the number of elements in HEX_buffer_message. It doesn't. It produces the size of the type of HEX_buffer_message which seems to be a 64 bit pointer yielding 8 rather than 7. There is no way to determine the size of an array allocated with new T[n] from the returned pointer. You'll need to use the n passed somehow.