HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppMinor

Send and receive data code

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
datacodereceiveandsend

Problem

I need to send and receive data. Here is solution for my original problem. I want to know how safe my finished code is and how I can improve it.

int sslWrite(SSL *ssl, const std::string &data)
{
    return sslWrite(ssl, &data[0], data.size());
}


int sslWrite(SSL *ssl, const void *buf, unsigned num)
{
    const int INT_SIZE = sizeof(int);
    const int numv = INT_SIZE + num;

    std::vector bufv(numv);

    memcpy(&bufv[0], &numv, INT_SIZE);
    if (num != 0) {
        memcpy(&bufv[INT_SIZE], buf, num);
    }

    int n = 0;
    while (n < num) {
        int w = SSL_write(ssl, &bufv[0], numv - n);
        if (w < 0) {
            return 0;
        }
        n += w;
    }

    return n;
}


const int BUF_INIT_SIZE = 0x10000;

std::vector sslRead(SSL *ssl)
{
    const int INT_SIZE = sizeof(int);
    std::vector bufv(BUF_INIT_SIZE);

    int m = SSL_read(ssl, &bufv.at(0), BUF_INIT_SIZE);

    if (m == 0) {
        return std::vector();
    }

    if (m (&bufv[0]);
    bufv.resize(n);

    while (m < n) {
        int k = SSL_read(ssl, &bufv.at(m), n - m);
        if (k < 0) {
            throw std::runtime_error("k < 0");
        }
        m += k;
    }

    bufv.resize(m);

    if (m < INT_SIZE) {
        throw std::runtime_error("m < INT_SIZE");
    }

    bufv.erase(bufv.begin(), bufv.begin() + INT_SIZE);
    return bufv;
}

Solution

-
Portability

The code would fail if the sender and receiver platforms disagree on the size of integer.

The code would fail if the sender and receiver platforms disagree on the endianness of integer.

-
Partial reads

There is a chance that the very first read returns just a couple of bytes. The code still interprets it as a valid integer.

-
Overall

There is no need to use the same buffer for both size and payload.

m,n,k are patently bad variable names.

-
Recommendations

Implement a separate send_size() and read_size() routines.

Context

StackExchange Code Review Q#100811, answer score: 4

Revisions (0)

No revisions yet.