由于IP黑白名单的限制,我们能访问的ip和域名资源非常有限,现将通过http协议授时方法整理如下:
#include <cstdio> #include <string.h> #include <curl/curl.h> #include <iostream> bool GetNetWorkingTime(const char* httpurl = "http://www.510link.com"); size_t readStringBuffFunction(char* data, size_t size, size_t nmemb, void* userStr); //解析data size_t readStringKey(const char* sourceChr, const char* key, char* returnChr); int main() { if (GetNetWorkingTime()) { std::cout << "ok" << std::endl; } else { printf("%s 向你问好!\n", "HttpClientTime"); } return 0; } /****************************************************************************** * Name : HttpClient::writeFunc * Author : cqnews * Version : V1.0.0 * Data : 2021.08.12 * Describe : 解析data ******************************************************************************/ size_t readStringBuffFunction(char* data, size_t size, size_t nmemb, void* userStr) { int res = -1; if (userStr != NULL) { ((std::string*)userStr)->append((char*)data, size * nmemb); return size * nmemb; } return res; } /****************************************************************************** * Name : HttpClient::GetNetWorkingTime * Author : cqnews * Version : V1.0.0 * Data : 2021.08.30 * Describe : 检查联网状态 ******************************************************************************/ bool GetNetWorkingTime(const char* httpurl) { //创建curl对象 CURL* curl; //创建curlcode对象 CURLcode res; bool ret = false; curl = curl_easy_init(); if (curl) { std::string readHeader = ""; //设置一个请求文件地址 curl_easy_setopt(curl, CURLOPT_URL, httpurl); curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 5);//设置超时时间 curl_easy_setopt(curl, CURLOPT_TIMEOUT, 5);//设置超时时间 curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, readStringBuffFunction); curl_easy_setopt(curl, CURLOPT_HEADERDATA, (void*)&readHeader); curl_easy_setopt(curl, CURLOPT_HEADER, 0); //只需要header头 curl_easy_setopt(curl, CURLOPT_NOBODY, 1); //不需要body curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1L); //执行请求操作,将返回值交给res res = curl_easy_perform(curl); //res=0的情况表示接收到信息,反之则没有收到信息 if (res == CURLE_OK) { std::cout << "readHeader1:" << readHeader << std::endl; readHeader = strstr(readHeader.c_str(), "Date: "); std::cout << "readHeader2:" << readHeader << std::endl; char dateChr1[30] = { 0 }; sscanf(readHeader.c_str(), "%[^\n]", dateChr1); std::cout << "dateChr1:" << dateChr1 << std::endl; char* dateChr2 = dateChr1; dateChr2 += strlen("Date: "); std::cout << "dateChr2:" << dateChr2 << std::endl; tm tm_; strptime(dateChr2, "%a, %d %b %Y %H:%M:%S GMT", &tm_); //将字符串转换为tm时间 tm_.tm_hour += 8; char buf[128] = { 0 }; strftime(buf, 64, "%Y-%m-%d %H:%M:%S", &tm_); std::cout << buf << std::endl; //已经联网 ret = true; } else { //没有联网 ret = false; } /* 释放资源 */ if (curl) { curl_easy_cleanup(curl); } } return ret; }
测试效果如下
标签:http,setopt,c++,char,easy,校时,curl,CURLOPT,size From: https://www.cnblogs.com/cqwo/p/17119860.html