Click to See Complete Forum and Search --> : send() +1


MasterDucky
November 8th, 2009, 08:18 AM
I dont really understand why we should add +1 to the buffer length in send().

If you send for example "hello" which is 5 bytes + 1 for the '\0'.

It will send "hello" + 1 byte which will be a garbage char because send() doesnt put '\0' at the end either.

send(mySocket, "hello", 6, 0);


So on the other side you will get (after making sure you got it all) "hello" + 1 garbage char.

So now if you do


buffer[i] = '\0';

you will put your '\0' after the garbage char because you have recieved 6 bytes.

So wouldnt it be better to send only strlen(buffer) without the +1 ?

hoxsiew
November 8th, 2009, 09:30 AM
First, you're wrong. The compiler will interpret "hello" as a char[6] and append a NULL terminator during compilation.

Without the NULL terminator, how are you going to know where the end of the string is? But more germane to the situation, you need to come up with a protocol for your data transfers when there is variable-length streams involved. You can always assume an upper bounds and use a fixed length buffer padded with zeros, or use a protocol that sends a size first, then the data stream.


int sz; //ensure in is the same size on both machines and platforms.
char buffer[100];

//...
strcpy(buffer,"Hello");
sz=strlen(buffer);
send(s,(char *)&sz,sizeof(int),0);
send(s,buffer,sz,0);

// receiving end:

int sz;
char *buffer;

//...

recv(s,&sz,sizeof(int),0);
buffer=new char[sz];
recv(s,buffer,sz,0);

//...
delete[] buffer;

MasterDucky
November 8th, 2009, 01:08 PM
Thank you very much for the explanation Hoxsiew!

Yes thats very interesting, "hello" wont even compile with [5] it need at least
[6] to compile.

char buf[5]= "hello";