如果一个连接服务器不断开,则curl_easy_perform会一直阻塞。这个时候就需要关闭或断开连接的方法。
常用的方法是设置连接超时,或者总超时,本处使用原始socket close
CURLINFO_ACTIVESOCKET - get the active socket
Example
CURL *curl = curl_easy_init();
if(curl) {
curl_socket_t sockfd;
curl_easy_setopt(curl, CURLOPT_URL, "https://example.com");
/* Do not do the transfer - only connect to host */
curl_easy_setopt(curl, CURLOPT_CONNECT_ONLY, 1L);
res = curl_easy_perform(curl);
/* Extract the socket from the curl handle */
res = curl_easy_getinfo(curl, CURLINFO_ACTIVESOCKET, &sockfd);
if(res != CURLE_OK) {
printf("Error: %s\n", curl_easy_strerror(res));
return 1;
}
}
另一个获取sock的方法
curl_easy_setopt(curl, CURLOPT_OPENSOCKETFUNCTION, my_opensocketfunc);
curl_socket_t my_opensocketfunc(void *clientp,curlsocktype purpose,struct curl_sockaddr *address)
{
curl_socket_t sock=socket(address->family, address->socktype, address->protocol);
printf("my_opensocketfunc sock = %d\n", sock);
return sock;
}
超时的配置见
CURLOPT_CONNECTTIMEOUT
Timeout for the connection phase. See CURLOPT_CONNECTTIMEOUT
CURLOPT_CONNECTTIMEOUT_MS
Millisecond timeout for the connection phase. See CURLOPT_CONNECTTIMEOUT_MS
CURLOPT_TIMEOUT
Timeout for the entire request. See CURLOPT_TIMEOUT