C - 如何正确使用OpenSSL的BIO_write()

时间:2013-01-11 19:53:55

标签: c network-programming openssl

我是OpenSSL的新手。我理解BIO_write(BIO * b,const void * buf,int len)需要在循环中调用,但我不完全确定我是否正确使用它。我写了这样一个函数:

int32_t SendPacket(BIO * const pBio, const unsigned char * const pPacket, const int nPacketLength)
{
    int32_t nPos = 0;

    if (!pBio || !pPacket || !nPacketLength)
        return -1;

    while (nPos < nPacketLength)
    {
        int32_t nNumberOfBytesWritten = BIO_write(pBio, &pPacket[nPos], nPacketLength - nPos);
        if (nNumberOfBytesWritten <= 0)
        {
            if (!BIO_should_retry(pBio))
                return -1;
        }
        else
        {
            nPos += nNumberOfBytesWritten;
        }
    }

    return nPos;
}

我正在考虑像这样使用它:

if (SendPacket(pBio, pPacket, nPacketLength) == nPacketLength)
{
    // Packet sent correctly.
}
else
{
    // Error occurred.
}

该功能看起来是否正确?任何反馈都表示赞赏。

1 个答案:

答案 0 :(得分:6)

在我原来的帖子中,我没有在重试BIO_write()时将“nNumberOfBytesWritten”重置为0.。

我最终做了这样的事情:

int32_t SendPacket(BIO * const pBio, const unsigned char * const pPacket, const int32_t nPacketLength)
{
    int32_t nPos = 0;
    int32_t nNumberOfBytesWritten = 0;
    ...
    for (nPos = 0; nPos < nPacketLength; nPos += nNumberOfBytesWritten)
    {
        if ((nNumberOfBytesWritten = BIO_write(pBio, pPacket + nPos, nPacketLength - nPos)) <= 0)
        {
            if (BIO_should_retry(pBio))
            {
                nNumberOfBytesWritten = 0;
                continue;
            }

            return -1;
        }
    }

    return nPos;
}