<分区>
编辑问题以包含 desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem .这将有助于其他人回答问题。
关闭 5 年前。
<分区>
编辑问题以包含 desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem .这将有助于其他人回答问题。
关闭 5 年前。
我遇到一个问题,我正在处理的程序会在调用 SSL_connect() 后立即关闭。我无法从中得到任何错误代码,因为之后调用 SSL_get_error() 将被忽略,因为它退出了程序。如果我只是用 connect() 做一个普通的 http 请求,它就可以正常工作。有人对此有任何想法吗?
我正在使用 Raspbian 的 Raspberry Pi 3 上运行它。 我是 SSL 的新手,因此非常感谢任何指点。
编辑:这是我正在尝试做的代码片段
#include <openssl/ssl.h>
#include <iostream>
#include <resolv.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <string>
#include <unistd.h>
int main()
{
int sockfd;
struct addrinfo hints, *servinfo, *p;
int rv;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
if ((rv = getaddrinfo("www.example.com", "https", &hints, &servinfo)) != 0)
{
fprintf(stderr, "getaddrinfo : %s\n", gai_strerror(rv));
exit(1);
}
SSL_load_error_strings();
SSL_library_init();
ssl_ctx = SSL_CTX_new(SSLv23_client_method());
SSL * connection = SSL_new(int sockfd;
struct addrinfo hints, *servinfo, *p;
int rv;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
if ((rv = getaddrinfo("www.example.com", "https", &hints, &servinfo)) != 0)
{
fprintf(stderr, "getaddrinfo : %s\n", gai_strerror(rv));
exit(1);
}
SSL_load_error_strings();
SSL_library_init();
ssl_ctx = SSL_CTX_new(SSLv23_client_method());
SSL * connection = SSL_new(ssl_ctx);
for (p = servinfo; p != NULL; p = p->ai_next)
{
if ((sockfd = socket(p->ai_family, p->ai_socktype,
p->ai_protocol)) == -1)
{
perror("socket");
continue;
}
int fd = SSL_set_fd(connection, sockfd);
break;
}
if (p == NULL)
{
// looped off the end of the list with no connection
fprintf(stderr, "failed to connect\n");
exit(2);
}
int connRet = 0;
while(connRet != 1 )
{
connRet = SSL_connect(connection);
cout << "Error : " << SSL_get_error(connection, connRet) << endl;
}
freeaddrinfo(servinfo);
return 0;
}
编辑 2:终于设法通过调试器运行它,现在我得到了:
(程序退出代码:141) 按回车键继续
根据这个问题:socket connection getting closed abruptly with code 141是 SIGPIPE 信号。
最佳答案
不确定为什么会导致崩溃,但是 SSL_connect
不等同于 connect
:它在已建立 上启动 TLS/SSL 握手> 连接。由于 sockfd
在您的代码中未连接,它会失败并将 connRet
设置为 -1,从而导致无限循环。
您应该在套接字创建后和启动 SSL 握手之前立即连接套接字:
if ((sockfd = socket(p->ai_family, p->ai_socktype,
p->ai_protocol)) == -1)
{
perror("socket");
continue;
}
/* connect at the TCP level */
if (connect(sockfd, servinfo->ai_addr, servinfo->ai_addrlen)) {
perror("connect");
continue;
}
int fd = SSL_set_fd(connection, sockfd);
...
但无论如何,您应该控制您的程序以消除可能的无限循环,并在错误消息中保持一致:使用 C++ 流 cout
或 C FILE* stderr
。如果可以打开,最好正确关闭套接字。
关于c++ - 程序在 SSL_connect 上退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45325038/