c - BIO_read 始终返回 0

标签 c openssl

我正在学习 OpenSSL 库。 这是我的代码

#include <openssl/ssl.h>
#include <openssl/bio.h>
#include <openssl/err.h>
#include <stdio.h>

void connect_openssl();

int main (int argc, char **argv)
{
    CRYPTO_malloc_init();
    SSL_library_init();
    SSL_load_error_strings();
    ERR_load_BIO_strings();
    OpenSSL_add_all_algorithms();

    connect_openssl();

    return 0;
}



void connect_openssl()
{
    BIO *bio = BIO_new_connect("google.com:80");
    char buffer[1024];

    if (bio == NULL)
    {
        printf("Error creating BIO! \n");
        //ERR_print_errors(stderr);
        return;
    }

    if (BIO_do_connect(bio) <= 0)
    {
        printf("Failed to connect! \n");
        return;
    }

    char buff[1024];;
    char send[1024];

    memset(send, 0, sizeof(send));
    strcat(send, "GET / HTTP/1.1\nHost:google.com\nUser Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)\nConnection: Close\n\n");

    BIO_puts(bio, send);

    while (1)
    {
        int x = BIO_read(bio, buff, sizeof(buff)-1);
        if (x == 0)
        {
            printf("x==0\n");
            break;
        }
        else if (x < 0)
        {
            if (! BIO_should_retry(bio))
            {
                printf("\nRead failed!\n");
                BIO_free_all(bio);
                return;
            }
        }
        else
        {
            buffer[x] = 0;
            printf("DATA:\n\n");
            printf("%s", buffer);
        }
    }

    BIO_free_all(bio);
    return;
}

问题是 BIO_read() 总是返回 0 值。有人能告诉我这段代码有什么问题吗?

最佳答案

自动回答: 啊,愚蠢的问题:/ 应用程序不正确工作的罪名是两行

buffer[x] = 0;
printf("%s", buffer);

应该是

buff[x] = 0;
printf("%s", buff);

当然,我需要更多的 sleep 。

关于c - BIO_read 始终返回 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6519865/

相关文章:

c - Valgrind 错误

openssl - 使用 RSA 公钥在 Openssl 中生成私钥?

ssl - LibrdKafka Producer 无法在 TLS 通信中与 KafkaBroker(Java) 通信

android - 一种监视 android 的 TLS 流量的方法

有人能告诉我哪里出了问题吗?我该如何替换 C 中的字符串?

c 可以按照 modula-2 定义 `TNumber = [minValue,maxValue]` 的方式定义数据类型吗?

c - XPutImage 出现问题

android - 为什么在 Xcode 6 中编译 C 库时会发生函数 'usleep' 的隐式声明在 C99 中无效?

c - 如何将 PFS 添加到用 c 和 openssl 编写的套接字服务器

c - 读取 OpenSSL ECDSA key 并将其写入 PEM 文件