首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >BIO_do_handshake返回%0

BIO_do_handshake返回%0
EN

Stack Overflow用户
提问于 2014-05-11 19:28:39
回答 1查看 316关注 0票数 0

我正在尝试编写一个非阻塞连接,当我使用下面的代码执行BIO_do_handshake()时,它总是返回0。我知道您不一定需要'do_handshake()',但似乎所有的事情都应该这样做,以确保握手完成。

我应该调用BIO_should_retry()吗?

代码语言:javascript
复制
void SSLAdaptor::Connect( SSL_CTX *ctx
                        , const std::string &hostname
                        , int port
                        , bool nonBlocking )
{

struct hostent *hp;
struct sockaddr_in addr;
SOCKET sockFD;

if( !( hp = gethostbyname( hostname.c_str() ) ) )
{
    return;
}

memset( &addr, 0, sizeof( addr ) );

addr.sin_addr= *( struct in_addr* )hp->h_addr_list[0];
addr.sin_family=AF_INET;
addr.sin_port=htons(port);

if( ( sockFD =socket( AF_INET, SOCK_STREAM, IPPROTO_TCP ) ) <0 )
{
    return;
}

if(connect(sockFD,(struct sockaddr *)&addr, sizeof(addr))<0)
{
    return;
}

SSL *ssl;
BIO *sbio;

ssl = SSL_new( ctx );

sbio = BIO_new_socket( sockFD, BIO_NOCLOSE );
SSL_set_bio( ssl, sbio, sbio );

if( SSL_connect( ssl ) <= 0 )
{
     return;
}

long hsReturn = BIO_do_handshake( sbio );

if ( hsReturn <= 0 ) 
{
    return;
}

}

我的(非阻塞) BIO读取返回垃圾:实际:↨♥+o 1E¿={²²∙?φáD‘öqñ↨≈☺预期:这是一条测试消息

代码语言:javascript
复制
int SSLSocket::BIORead( std::string &buffer, const int size )
{
int bytesRead = -1;
std::vector<char> readBuffer(size);

std::cout << "Before BIO_read() call" << std::endl;
bytesRead = BIO_read( m_bio, readBuffer.data(), size );
std::cout << "After BIO_read() call" << std::endl;
std::cout << "BIO_read() read   : " << bytesRead << " bytes" << std::endl;

std::string tmpBuffer = std::string( readBuffer.begin(), readBuffer.end() );
std::cout << "BIO_read() buffer : " << tmpBuffer << " bytes" << std::endl;

if ( bytesRead < 0 ) 
{
    //  Check if should retry read, if not then an error on the connection
    //  has occurred and the user notified.
    if ( BIO_should_retry( m_bio ) )
    {
        bytesRead = 0;
    }
    else
    {
      // real error
      bytesRead = -1;
  }
}
else if ( bytesRead == 0 ) 
{
    //  Nothing was read
    bytesRead = 0;
}
else
{
    buffer = std::string( readBuffer.begin(), readBuffer.end() );
}

return bytesRead;
}
EN

回答 1

Stack Overflow用户

发布于 2014-05-12 02:13:16

SSL_connect已经做了握手,但你必须正确地使用它与非阻塞套接字,例如,检查SSL_ERROR_WANT_READ,SSL_ERROR_WANT_WRITE,并等待所需的条件,只要SSL_connect返回<0。因此不需要调用BIO_do_handshake。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23592013

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档