How to empty the variable buffer in recv() before accepting a string.

A

Aditya

Hi
I am using recv() from socket.h in one of my TCP-client projects.
The problem is that the buffer variable in recv(socketDescriptor,
buffer, flags) points to some stray location and when the incoming
string is filled into it, there are trailing junk characters also.

The code portion refering to it is somewhat like:

int rcvStatus;
char *buffer;
rcvStatus = recv(socketDescriptor, buffer, flags);
std::cout<< buffer << std::endl;

If I initialize the buffer variable to NULL or "0", the recv() returns
-1, that is it doesn't accept the incoming string.
So, Please help me to clean the buffer variable, before it is being
filled with the incoming string.

Thanks
Aditya
 
L

linarin

the following will work:
int len = 1024;
char buffer[1024 + 1];
len = recv(socketDescriptor, buffer, len,flags);
if (len > 0){
//there is actual data received.
buffer[len] = '\0';
//process the data in buffer.
}else if (len == 0){
//the connection has closed.
}else{
//unknown error occur.
}
 
A

Archie

Hi
I am using recv() from socket.h in one of my TCP-client projects.
The problem is that the buffer variable in recv(socketDescriptor,
buffer, flags) points to some stray location and when the incoming
string is filled into it, there are trailing junk characters also.

The code portion refering to it is somewhat like:

int rcvStatus;
char *buffer;
rcvStatus = recv(socketDescriptor, buffer, flags);

What is the size of the buffer? Typically you should allocate a
buffer of some size either on the stack or heap and then pass this
size to recv as the 3rd arg. recv on success returns the number of
bytes received. You should then read only those many bytes from the
buffer passed to recv. Hope his helps.
 
I

Ian Collins

Aditya said:
Hi
I am using recv() from socket.h in one of my TCP-client projects.

Please don't multi-post on Usenet, as you where told elsewhere, this
belongs on comp.unix.programmer.
 
A

Aditya

What is the size of the buffer? Typically you should allocate a
buffer of some size either on the stack or heap and then pass this
size to recv as the 3rd arg. recv on success returns the number of
bytes received. You should then read only those many bytes from the
buffer passed to recv. Hope his helps.






- Show quoted text -

Hi
Thanks
That Helps....
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top