5

I want to use the function recv(socket, buf, len, flags) to receive an incoming packet. However I do not know the length of this packet prior to runtime so the first 8 bytes are supposed to tell me the length of this packet. I don't want to just allocate an arbitrarily large len to accomplish this so is it possible to set len = 8 have buf be a type of uint64_t. Then afterwards

memcpy(dest, &buf, buf)?

2
  • Why don't you want to allocate an arbitrarily large buffer? If the data isn't going to stay around for very long, why does it matter how large the buffer is? And if the data is going to stay around for awhile, what's the problem with copying it into another buffer once you know the size? Mar 1, 2016 at 22:25
  • Note that with an 8-byte length field, either the upper 4 bytes are always going to be zero (and thus unused/meaningless) or you're occasionally going to be allocating receive-buffers that are > 4GB long (possibly much greater!). I'm not sure which possibility is worse :) Jul 1, 2021 at 21:27

4 Answers 4

5

Since TCP is stream-based, I'm not sure what type of packages you mean. I will assume that you are referring to application level packages. I mean packages which are defined by your application and not by underlying protocols like TCP. I will call them messages instead to avoid confusion.

I will show two possibilities. First I will show, how you could read a message without knowing the length before you have finished reading. The second example will do two calls. First it reads the size of the message. Then it read the whole message at once.


Read data until the message is complete

Since TCP is stream-based, you will not loss any data when your buffer is not big enough. So you can read a fixed amount of bytes. If something is missing, you can call recv again. Here is a extensive example. I just wrote it without testing. I hope everything would work.

std::size_t offset = 0;
std::vector<char> buf(512);

std::vector<char> readMessage() {
    while (true) {
        ssize_t ret = recv(fd, buf.data() + offset, buf.size() - offset, 0);
        if (ret < 0) {
            if (errno == EINTR) {
                // Interrupted, just try again ...
                continue;
            } else {
                // Error occured. Throw exception.
                throw IOException(strerror(errno));
            }
        } else if (ret == 0) {
            // No data available anymore.
            if (offset == 0) {
                // Client did just close the connection
                return std::vector<char>(); // return empty vector
            } else {
                // Client did close connection while sending package?
                // It is not a clean shutdown. Throw exception.
                throw ProtocolException("Unexpected end of stream");
            }
        } else if (isMessageComplete(buf)) {
            // Message is complete.
            buf.resize(offset + ret); // Truncate buffer
            std::vector<char> msg = std::move(buf);
            std::size_t msgLen = getSizeOfMessage(msg);
            if (msg.size() > msgLen) {
                // msg already contains the beginning of the next message.
                // write it back to buf
                buf.resize(msg.size() - msgLen)
                std::memcpy(buf.data(), msg.data() + msgLen, msg.size() - msgLen);
                msg.resize(msgLen);
            }
            buf.resize(std::max(2*buf.size(), 512)) // prepare buffer for next message
            return msg;
        } else {
            // Message is not complete right now. Read more...
            offset += ret;
            buf.resize(std::max(buf.size(), 2 * offset)); // double available memory
        }
    }
}

You have to define bool isMessageComplete(std::vector<char>) and std::size_t getSizeOfMessage(std::vector<char>) by yourself.

Read the header and check the length of the package

The second possibility is to read the header first. Just the 8 bytes which contains the size of the package in your case. After that, you know the size of the package. This mean you can allocate enough storage and read the whole message at once:

/// Reads n bytes from fd.
bool readNBytes(int fd, void *buf, std::size_t n) {
    std::size_t offset = 0;
    char *cbuf = reinterpret_cast<char*>(buf);
    while (true) {
        ssize_t ret = recv(fd, cbuf + offset, n - offset, MSG_WAITALL);
        if (ret < 0) {
            if (errno != EINTR) {
                // Error occurred
                throw IOException(strerror(errno));
            }
        } else if (ret == 0) {
            // No data available anymore
            if (offset == 0) return false;
            else             throw ProtocolException("Unexpected end of stream");
        } else if (offset + ret == n) {
            // All n bytes read
            return true;
        } else {
            offset += ret;
        }
    }
}

/// Reads message from fd
std::vector<char> readMessage(int fd) {
    std::uint64_t size;
    if (readNBytes(fd, &size, sizeof(size))) {
        std::vector buf(size);
        if (readNBytes(fd, buf.data(), size)) {
            return buf;
        } else {
            throw ProtocolException("Unexpected end of stream");
        }
    } else {
        // connection was closed
        return std::vector<char>();
    }
}

The flag MSG_WAITALL requests that the function blocks until the full amount of data is available. However, you cannot rely on that. You have to check it and read again if something is missing. Just like I did it above.

readNBytes(fd, buf, n) reads n bytes. As far as the connection was not closed from the other side, the function will not return without reading n bytes. If the connection was closed by the other side, the function returns false. If the connection was closed in the middle of a message, an exception is thrown. If an i/o-error occurred, another exception is thrown.

readMessage reads 8 bytes [sizeof(std::unit64_t)] und use them as size for the next message. Then it reads the message.

If you want to have platform independency, you should convert size to a defined byte order. Computers (with x86 architecture) are using little endian. It is common to use big endian in network traffic.

Note: With MSG_PEEK it is possible to implement this functionality for UDP. You can request the header while using this flag. Then you can allocate enough space for the whole package.

2

A fairly common technique is to read leading message length field, then issue a read for the exact size of the expected message.

HOWEVER! Do not assume that the first read will give you all eight bytes(see Note), or that the second read will give you the entire message/packet.

You must always check the number of bytes read and issue another read (or two (or three, or...)) to get all the data you want.

Note: Because TCP is a streaming protocol and because the packet size "on the wire" varies in accordance with a very arcane algorithm designed to maximize network performance, you could easily issue a read for eight bytes and the read could return having only read three (or seven or ...) bytes. The guarantee is that unless there is an unrecoverable error you will receive at least one byte and at most the number of bytes you requested. Because of this you must be prepared to do byte address arithmetic and issue all reads in a loop that repeats until the desired number of bytes is returned.

3
  • Sorry could you clarify on what you mean by not assuming that the first read will give you all eight bytes? I'm writing this as part of an exercise and I can expect all incoming packets to have the first 8 bytes to be the length field of the packet. Mar 1, 2016 at 20:03
  • @MathisHard I edited the answer to add a note explaining why you may receive fewer bytes of data than you asked for -- even when reading the message length header. Mar 1, 2016 at 20:11
  • @MathisHard You shouldn't have any particular expectations about what the packets will be like. And even if you did, you shouldn't have any particular expectations about how packets should map to calls to recv either. TCP provides the application with a bidirectional byte stream, not a packet or message interface. Mar 1, 2016 at 22:24
1

Since TCP is streaming there isn't really any end to the data you receive, not until the connection is closed or there is an error.

Instead you need to implement your own protocol on top of TCP, one that either contains a specific end-of-message marker, a length-of-data header field, or possibly a command-based protocol where the data of each command is of a well-known size.

That way you can read into a small fixed-sized buffer and append to a larger (possibly expanding) buffer as needed. The "possibly expanding" part is ridiculously easy in C++, what with std::vector and std::string (depending on the data you have)

There is another important thing to remember, that since TCP is stream-based, a single read or recv call may not actually fetch all the data you request. You need to receive the data in a loop until you have received everything.

4
  • so something like while( recv(socket, buf, len, flags) > 0) {...}? Mar 1, 2016 at 20:05
  • @MathisHard Something along those lines yes. Mar 1, 2016 at 20:08
  • That way you can read into a small fixed-sized buffer and append to a larger (possibly expanding) buffer as needed. yeah, sure. Why not copy every chunk of data twice. But why stop at that? Let's copy it three times!
    – SergeyA
    Mar 1, 2016 at 20:14
  • Or you can read into small (possibly fixed size) buffers and collect them into a std::vector, possibly also storing some flag to detect when a message is complete, and then just process the entire message iterating through the vector. Thus no appending of bytes and resizing of byte buffers required (although processing the message might become less straight-forward; depending on what you want to do with the bytes). Feb 2, 2017 at 11:44
0

In my Personal opinion.

I suggest receive "size of message"(integer 4 byte fixed) first.

recv(socket, "size of message written in integer" , "size of integer")

then

receive real message after.

recv(socket, " real message" ,"size of message written in integer")

This techinique also can be used on "sending files, images ,long messages"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.