I'm creating a program that connects to an IP address on a specific port, then uses the recv() function to return the data from the address. I don't know how to go about creating the buffer the data will save to. At first I was just going to create a char array for it to save to, but then I would run the risk for buffer overflow. Next, I considered having the user input the number of bytes to receive. This would work, but would be impractical when dealing with a large amount of data or when retrieving an unknown amount of data. Would there be a way to set an array up at a certain size, then as soon as it is full, print it to stdout, then clear it out and start writing from the beginning? I am worried that while the array is being printed and cleared, more data would be received and lost. Any suggestions?

I've never done anything of this caliber, still very new to C++, but it sounds to me like this could be done by using a Link List, just keep adding new Nodes until you've gotten all the information you need.

(First time trying to help someone, sorry if I sound dumb)

I found a bit of useful info on MDSN:

For connection-oriented sockets (type SOCK_STREAM for example), calling recv will return as much data as is currently available—up to the size of the buffer specified.

I'm using SOCK_STREAM, so this means I don't have to worry about buffer overflow as much. It also makes using a buffer more difficult. I have to specify the size of the buffer in the recv() function. (For reference, this is the function:

int recv(
  __in   SOCKET s,
  __out  char *buf,
  __in   int len,
  __in   int flags
);

Parameters
s
The descriptor that identifies a connected socket.

buf
A pointer to the buffer to receive the incoming data.

len
The length, in bytes, of the buffer pointed to by the buf parameter.

flags
A set of flags that influences the behavior of this function.)

I guess this means if I specify the size of the buffer, it will cut off the message as soon as it sends enough data to fill the buffer once. Why does it have to be so complicated...

I found even MORE interesting info. According to experts-exchange.com:

For a stream connection, such as is used for telnet, http, ftp, mail, news, there is NO PROBLEM.
Just read as much as you'd like, the remainder will remain in the TCP stack's buffer.

Meaning zero chance for buffer overflow. It's going to be a lot easier to figure out from here.

This article has been dead for over six months. Start a new discussion instead.