Send and receive data code using OpenSSL 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. Here is my first try. Now I need to get review for my new code.  

void sslWrite(SSL *ssl, const void *buf, unsigned size)
{
    int writedTotal = 0;
    const char *ccBuf = reinterpret_cast&lt;const char *&gt;(buf);

    while (writedTotal &lt; size) {
        int writedPart = SSL_write(ssl, ccBuf + writedTotal, size - writedTotal);
        if (writedPart &lt; 0) {
            std::string error = "SSL_write error = ";
            error += (std::to_string(writedPart) + ".");
            throw std::runtime_error(error);
        }
        writedTotal += writedPart;
    }
}

std::vector&lt;char&gt; sslRead(SSL *ssl, unsigned size)
{
    std::vector&lt;char&gt; ret(size);
    unsigned readTotal = 0;

    while (readTotal &lt; size) {
        int readPart = SSL_read(ssl, &amp;ret[readTotal], size - readTotal);
        if (readPart &lt; 0) {
            std::string error = "SSL_read error = ";
            error += (std::to_string(readPart) + ".");
            throw std::runtime_error(error);
        }
        readTotal += readPart;
    }

    return ret;
}

void sslWriteSize(SSL *ssl, unsigned size)
{
    if (sizeof(u_long) &gt; 8)
        throw std::runtime_error("Write size error.");

    u_long nlSize = htonl(size);
    sslWrite(ssl, &amp;nlSize, 8);
}

unsigned sslReadSize(SSL *ssl)
{
    if (sizeof(u_long) &gt; 8)
        throw std::runtime_error("Read size error.");

    u_long size = *reinterpret_cast&lt;u_long *&gt;(&amp;sslRead(ssl, 8)[0]);
    size = ntohl(size);
    return size;
}

void sslWrite(SSL *ssl, const std::string &amp;data)
{
    if (data.empty())
        throw std::runtime_error("SSL write error. Data is empty.");

    sslWriteSize(ssl, data.size());
    sslWrite(ssl, &amp;data.at(0), data.size());
}

std::vector&lt;char&gt; sslRead(SSL *ssl)
{
    unsigned size = sslReadSize(ssl);
    return sslRead(ssl, size);
}


Is there a buffering problem as in my old code?
Looks good. No buffering problems anymore. Endianness is handled correctly. Reading and writing size is duly factored out.

The only suggestion is not rely on the native unsigned type to represent the size. Notice that htonl takes uint32_t as a parameter. It is a strong hint to pass size as uint32_t as well. This guarantees that the size is 4 byte long no matter which platform it is running on. Don't forget to #include &lt;cstdint&gt;.