环境:ubuntu 1604
需要使用C++进行网络通信,选择使用curl库
编译的时候,报了链接错误。
这里记录一下Linux上安装curl的过程。
1. 去这个网站:https://curl.haxx.se/download.html 下载最新的curl压缩包,我这里是7.60
2. 解压: tar -zxf curl-7.60.0.tar.gz
3. 进入当前目录: cd curl-7.60.0/
4. 依次输入如下命令:
./configure
make
sudo make install
5. 等待完成即可
6. terminal输入 g++ main.cpp -lcurl,即可看到默认的a.out文件生成啦
一个例子代码:
#include #include #include size_t CurlWrite_CallbackFunc_StdString(void *contents, size_t size, size_t nmemb, std::string *s)
{
size_t newLength = size*nmemb;
size_t oldLength = s->size();
try
{
s->resize(oldLength + newLength);
}
catch(std::bad_alloc &e)
{
//handle memory problem
return 0;
}
std::copy((char*)contents,(char*)contents+newLength,s->begin()+oldLength);
return size*nmemb;
}
int main()
{
CURL *curl;
CURLcode res;
//curl_global_init(CURL_GLOBAL_DEFAULT);
curl = curl_easy_init();
std::string s;
// while (){
//
// }
if(curl)
{
curl_easy_setopt(curl, CURLOPT_URL, "http://47.89.179.202:5000/turn/2");
// curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L); //only for https
// curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L); //only for https
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlWrite_CallbackFunc_StdString);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &s);
/* Perform the request, res will get 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);
}
std::cout<
参考资料:
https://curl.haxx.se/docs/install.html