操作系统:CentOS 7.6。
为了方便,直接使用yum安装:yum install libcurl-devel.
Installed:
libcurl-devel.x86_64 0:7.29.0-59.el7_9.2Dependency Updated:
curl.x86_64 0:7.29.0-59.el7_9.2 libcurl.x86_64 0:7.29.0-59.el7_9.2
可以看到安装的版本是7.29, 比最新版本8.71低。不过没关系,7.29够用了。
接下来就是测试demo了。
从官网现在examples,下载https.c:
#include <stdio.h>
#include <curl/curl.h>
int main(void)
{
CURL *curl;
CURLcode res;
curl_global_init(CURL_GLOBAL_DEFAULT);
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, "https://www.baidu.com/");
#ifdef SKIP_PEER_VERIFICATION
/*
* If you want to connect to a site who is not using a certificate that is
* signed by one of the certs in the CA bundle you have, you can skip the
* verification of the server's certificate. This makes the connection
* A LOT LESS SECURE.
*
* If you have a CA cert for the server stored someplace else than in the
* default bundle, then the CURLOPT_CAPATH option might come handy for
* you.
*/
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
#endif
#ifdef SKIP_HOSTNAME_VERIFICATION
/*
* If the site you are connecting to uses a different host name that what
* they have mentioned in their server certificate's commonName (or
* subjectAltName) fields, libcurl refuses to connect. You can skip this
* check, but it makes the connection insecure.
*/
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
#endif
/* cache the CA cert bundle in memory for a week */
// 从7.87版本才开始支持这个选项,先注释掉
//curl_easy_setopt(curl, CURLOPT_CA_CACHE_TIMEOUT, 604800L);
/* Perform the request, res gets the return code */
res = curl_easy_perform(curl);
/* Check for errors */
if(res != CURLE_OK)
fprintf(stderr, "curl_easy_perform() failed: %s\n",
curl_easy_strerror(res));
/* always cleanup */
curl_easy_cleanup(curl);
}
curl_global_cleanup();
return 0;
}
直接在shell中使用命令行编译:
g++ https.c -lssl -lcrypto -lcurl
由于libcurl-devel安装到系统目录下了,所以不需要指定头文件目录和库目录,直接连接就行了。在编译的过程中注释掉了一行代码 ,这是由于linux安装的库版本比example版本更低导致的。
// 从7.87版本才开始支持这个选项,先注释掉
//curl_easy_setopt(curl, CURLOPT_CA_CACHE_TIMEOUT, 604800L);
编译和运行都很顺利。