无法使用OpenSSL BIO接口建立连接

时间:2013-04-12 13:12:40

标签: c networking openssl connection

我正在VS2010中调试。以下代码中的BIO_do_connect()失败。我做错了什么?

(pBio在使用前已正确设置)

static const uint32_t kuSleepIntervalInMs = 50;

...
uint32_t uTimeTaken = 0;
...

BIO_set_nbio(pBio, 1);

for (;;)
{
    if (uTimeTaken > 10000)
        return ERR_CONNECTION_TIMED_OUT;

    if (BIO_do_connect(pBio) > 0)
        break;

    if (BIO_should_retry(pBio))
    {
        Sleep(kuSleepIntervalInMs);

        uTimeTaken += kuSleepIntervalInMs;

        continue;
    }

    BIO_free_all(pBio);

    return ERR_FAILED_TO_ESTABLISH_CONNECTION;
}

看来如果我增加睡眠间隔(例如500),BIO_do_connect工作正常,但我想知道它为什么失败,间隔值更短。

1 个答案:

答案 0 :(得分:0)

自发布原始问题以来,我已切换到使用select(),因此问题不再有效。

而不是做

uTimeTaken += kuSleepIntervalInMs;

我现在正在做:

int nRet;
int fdSocket;
fd_set connectionfds;
struct timeval timeout;

BIO_set_nbio(pBio, 1);

nRet = BIO_do_connect(pBio);

if ((nRet <= 0) && !BIO_should_retry(pBio))
    // failed to establish connection.

if (BIO_get_fd(pBio, &fdSocket) <= 0)
    // failed to get fd.

if (nRet <= 0)
{
    FD_ZERO(&connectionfds);
    FD_SET(fdSocket, &connectionfds);

    timeout.tv_usec = 0;
    timeout.tv_sec = 10;

    nRet = select(fdSocket + 1, NULL, &connectionfds, NULL, &timeout);
    if (nRet == 0)
        // timeout has occurred.
}

查看我的其他post