123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160 |
- #include <stdio.h>
- #include <string.h>
- #include <curl/curl.h>
- static int wait_on_socket(curl_socket_t sockfd, int for_recv, long timeout_ms)
- {
- struct timeval tv;
- fd_set infd, outfd, errfd;
- int res;
- tv.tv_sec = timeout_ms / 1000;
- tv.tv_usec = (timeout_ms % 1000) * 1000;
- FD_ZERO(&infd);
- FD_ZERO(&outfd);
- FD_ZERO(&errfd);
- FD_SET(sockfd, &errfd);
- if(for_recv) {
- FD_SET(sockfd, &infd);
- }
- else {
- FD_SET(sockfd, &outfd);
- }
-
- res = select((int)sockfd + 1, &infd, &outfd, &errfd, &tv);
- return res;
- }
- int main(void)
- {
- CURL *curl;
- CURLcode res;
-
- const char *request = "GET / HTTP/1.0\r\nHost: example.com\r\n\r\n";
- size_t request_len = strlen(request);
- curl_socket_t sockfd;
- size_t nsent_total = 0;
-
- curl = curl_easy_init();
- if(curl) {
- curl_easy_setopt(curl, CURLOPT_URL, "http://example.com");
-
- curl_easy_setopt(curl, CURLOPT_CONNECT_ONLY, 1L);
- res = curl_easy_perform(curl);
- if(res != CURLE_OK) {
- printf("Error: %s\n", curl_easy_strerror(res));
- return 1;
- }
-
- res = curl_easy_getinfo(curl, CURLINFO_ACTIVESOCKET, &sockfd);
- if(res != CURLE_OK) {
- printf("Error: %s\n", curl_easy_strerror(res));
- return 1;
- }
- printf("Sending request.\n");
- do {
-
- size_t nsent;
- do {
- nsent = 0;
- res = curl_easy_send(curl, request + nsent_total,
- request_len - nsent_total, &nsent);
- nsent_total += nsent;
- if(res == CURLE_AGAIN && !wait_on_socket(sockfd, 0, 60000L)) {
- printf("Error: timeout.\n");
- return 1;
- }
- } while(res == CURLE_AGAIN);
- if(res != CURLE_OK) {
- printf("Error: %s\n", curl_easy_strerror(res));
- return 1;
- }
- printf("Sent %" CURL_FORMAT_CURL_OFF_T " bytes.\n",
- (curl_off_t)nsent);
- } while(nsent_total < request_len);
- printf("Reading response.\n");
- for(;;) {
-
- char buf[1024];
- size_t nread;
- do {
- nread = 0;
- res = curl_easy_recv(curl, buf, sizeof(buf), &nread);
- if(res == CURLE_AGAIN && !wait_on_socket(sockfd, 1, 60000L)) {
- printf("Error: timeout.\n");
- return 1;
- }
- } while(res == CURLE_AGAIN);
- if(res != CURLE_OK) {
- printf("Error: %s\n", curl_easy_strerror(res));
- break;
- }
- if(nread == 0) {
-
- break;
- }
- printf("Received %" CURL_FORMAT_CURL_OFF_T " bytes.\n",
- (curl_off_t)nread);
- }
-
- curl_easy_cleanup(curl);
- }
- return 0;
- }
|