cpp-httplib 中的 HTTPS 给 Segfault

Posted

技术标签:

【中文标题】cpp-httplib 中的 HTTPS 给 Segfault【英文标题】:HTTPS Giving Segfault in cpp-httplib 【发布时间】:2020-08-03 10:23:07 【问题描述】:

我正在尝试使用 cpp-httplib 执行一些 HTTP(S) 请求。为什么

#include <iostream>
#include "httplib.h"

using namespace std;

int main()

    cout << "hi" << endl;

    auto res = httplib::Client("http://***.com").Get("/");
    cout << res << endl;

    return 0;

打印

hi
0x5605c058db50

(好的),但是

#include <iostream>
#include "httplib.h"

using namespace std;

int main()

    cout << "hi" << endl;

    auto res = httplib::Client("https://***.com").Get("/");
    cout << res << endl;

    return 0;

(相同的代码,只是将http更改为https

hi
Segmentation fault (core dumped)

?

GDB backtrace 在段错误之后给了我这个:

#0  0x000055555555eee8 in httplib::ClientImpl::Socket::is_open (this=0x50) at /home/viktor/delayWatcher/cpp-fetcher/libs/httplib.h:822
#1  0x0000555555569a20 in httplib::ClientImpl::send (this=0x0, req=..., res=...) at /home/viktor/delayWatcher/cpp-fetcher/libs/httplib.h:4579
#2  0x000055555556bb8b in httplib::ClientImpl::Get(char const*, std::multimap<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, httplib::detail::ci, std::allocator<std::pair<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > > > > const&, std::function<bool (unsigned long, unsigned long)>) (this=0x0, path=0x5555555bc887 "/", headers=std::multimap with 0 elements, progress=...) at /home/viktor/delayWatcher/cpp-fetcher/libs/httplib.h:4980
#3  0x000055555556ba1d in httplib::ClientImpl::Get (this=0x0, path=0x5555555bc887 "/") at /home/viktor/delayWatcher/cpp-fetcher/libs/httplib.h:4958
#4  0x000055555556c345 in httplib::Client::Get (this=0x7fffffffe320, path=0x5555555bc887 "/") at /home/viktor/delayWatcher/cpp-fetcher/libs/httplib.h:6015
#5  0x000055555555d767 in main () at /home/viktor/delayWatcher/cpp-fetcher/fetcher/main.cpp:11

【问题讨论】:

【参考方案1】:

按照cpp-httplib github 上的自述文件:

添加#define CPPHTTPLIB_OPENSSL_SUPPORT, 链接libssllibcrypto

所以代码是这样的:

#include <iostream>

#define CPPHTTPLIB_OPENSSL_SUPPORT

#include "httplib.h"

using namespace std;

int main()

    cout << "hi" << endl;

    auto res = httplib::Client("https://***.com").Get("/");
    cout << res << endl;

    return 0;

在我的情况下,运行g++,最后是-lssl -lcrypto

我尝试过但(可能很明显?)错误:#define 需要在 #include "httplib.h" 之前。

// WRONG order, still segfault
#include "httplib.h"

#define CPPHTTPLIB_OPENSSL_SUPPORT

【讨论】:

以上是关于cpp-httplib 中的 HTTPS 给 Segfault的主要内容,如果未能解决你的问题,请参考以下文章

如何正确链接/包含 c++ 库

Java SE之基础篇——面向对象

[Js-Java SE]Java中的Native关键字与JNI

Java SE之基础篇——ArrayList类详解

Java SE之基础篇——IDEA中DeBug调试以及综合案例练习

Java SE之基础篇——IDEA中DeBug调试以及综合案例练习