3

我是 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.
}

函数看起来正确吗?任何反馈表示赞赏。

4

1 回答 1

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;
}
于 2013-04-16T11:02:46.123 回答