views:

76

answers:

3

I am given the following declaration:

char inbuff[500], *ptr;

int n, bufferlen;

Write a program segement to receive a message having 500 bits from the TCP socket sock and store this message in inbuff.

My answer is:

n = recv( sock, inbuff, strlen( inbuff ), 0 );

However, I am not sure why *ptr is given in the declaration.

So, I would like ask, what is the purpose of the pointer in this question??

Or my program segement is wrong?

Thank you for all of yours help first!

A: 

Your code fragment has some errors. As James mentioned, you need sizeof, not strlen to get the size of your buffer. But more importantly, recv doesn't work quite the way you think it does. Make sure you understand exactly what guarantees it makes.

Peter Ruderman
Sorry, I changed my comment just before you posted this. He really wants to use `bufferlen`; I didn't see that he had that variable until I formatted his code.
James McNellis
+1  A: 

recv can return less than data than you requested, if the requested amount of data hasn't arrived yet (the return value is the exact amount received) -- so you need to put the program in a loop, and use p to point to the next location for more data, until you fill the buffer.

In Linux, there's a MSG_WAITALL flag that tries to limit this behavior, but it's not perfect:

   MSG_WAITALL (since Linux 2.2)
          This flag requests that  the  operation  block  until  the  full
          request  is  satisfied.  However, the call may still return less
          data than requested if a signal is caught, an error  or  discon‐
          nect  occurs,  or the next data to be received is of a different
          type than that returned.
Ken Bloom
recv doesn't actually request a specific amount of data - it just gives the size of the buffer.
kyoryu
@kyoryu: I guess that's a better way to think about it.
Ken Bloom
A: 

The ptr is probably not usefull, however I would use n = recv(sock, inbuff, 500, 0); because strlen(inbuff); won't necessarily be 500;

Duracell
ptr is necessary... see Ken Bloom's answer as to why it is. OTOH, you're correct on strlen. So, +1 and -1... I guess that balances out :)
kyoryu