SpartacusIn21

专注:c++,python,d3d,设计模式,人工智能,并行计算

curl/libcurl获取打开网页平均网速

CURL:

curl -o /dev/null -s -w %{http_code}:%{http_connect}:%{content_type}:%{time_namelookup}:%{time_redirect}:%{time_pretransfer}:%{time_connect}:%{time_starttransfer}:%{time_total}:%{speed_download} baidu.com

LIBCURL: 

size_t WriteCallback(void *ptr, size_t size, size_t nmemb, void *data)
{
    /* we are not interested in the downloaded bytes itself,
    so we only return the size we would have saved ... */
    (void)ptr;  /* unused */
    (void)data; /* unused */
    return (size_t)(size * nmemb);
}


//获取下载网速 float GetDownloadSpeed(const string &strURL) { #define CHKSPEED_VERSION "1.0" CURL *curl = curl_easy_init(); float fNetSpeed = -1; if (curl) { curl_easy_setopt(curl, CURLOPT_URL, strURL.c_str()); /* send all data to this function */ curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback); if (strURL.find("https:") != string::npos) { curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L); curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L); } /* some servers don't like requests that are made without a user-agent field, so we provide one */ curl_easy_setopt(curl, CURLOPT_USERAGENT, "libcurl-speedchecker/" CHKSPEED_VERSION); /* Perform the request */ CURLcode res = curl_easy_perform(curl); if (!res) { double speed; res = curl_easy_getinfo(curl, CURLINFO_SPEED_DOWNLOAD, &speed); if (!res) { fNetSpeed = speed / 1024.0;//kbyte/sec } } } /* cleanup curl stuff */ curl_easy_cleanup(curl); return fNetSpeed; }

  

 

参考资料:

https://curl.haxx.se/libcurl/c/chkspeed.html

posted on 2017-12-18 16:29  SpartacusIn21  阅读(708)  评论(0编辑  收藏  举报

导航