Resync
[CMakeLuaTailorHgBridge.git] / CMakeLua / Utilities / cmcurl-7.19.0 / docs / examples / sendrecv.c
blobf8bd89942a7eeac5acef96ef9168f35446a94c06
1 /*****************************************************************************
2 * _ _ ____ _
3 * Project ___| | | | _ \| |
4 * / __| | | | |_) | |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * An example of curl_easy_send() and curl_easy_recv() usage.
10 * $Id: sendrecv.c,v 1.1.1.1 2008-09-23 16:32:05 hoffman Exp $
13 #include <stdio.h>
14 #include <string.h>
15 #include <curl/curl.h>
17 /* Auxiliary function that waits on the socket. */
18 static int wait_on_socket(int sockfd, int for_recv, long timeout_ms)
20 struct timeval tv;
21 fd_set infd, outfd, errfd;
22 int res;
24 tv.tv_sec = timeout_ms / 1000;
25 tv.tv_usec= (timeout_ms % 1000) * 1000;
27 FD_ZERO(&infd);
28 FD_ZERO(&outfd);
29 FD_ZERO(&errfd);
31 FD_SET(sockfd, &errfd); /* always check for error */
33 if(for_recv)
35 FD_SET(sockfd, &infd);
37 else
39 FD_SET(sockfd, &outfd);
42 /* select() returns the number of signalled sockets or -1 */
43 res = select(sockfd + 1, &infd, &outfd, &errfd, &tv);
44 return res;
47 int main(void)
49 CURL *curl;
50 CURLcode res;
51 /* Minimalistic http request */
52 const char *request = "GET / HTTP/1.0\r\nHost: curl.haxx.se\r\n\r\n";
53 int sockfd; /* socket */
54 size_t iolen;
56 curl = curl_easy_init();
57 if(curl) {
58 curl_easy_setopt(curl, CURLOPT_URL, "curl.haxx.se");
59 /* Do not do the transfer - only connect to host */
60 curl_easy_setopt(curl, CURLOPT_CONNECT_ONLY, 1L);
61 res = curl_easy_perform(curl);
63 if(CURLE_OK != res)
65 printf("Error: %s\n", strerror(res));
66 return 1;
69 /* Extract the socket from the curl handle - we'll need it
70 * for waiting */
71 res = curl_easy_getinfo(curl, CURLINFO_LASTSOCKET, &sockfd);
73 if(CURLE_OK != res)
75 printf("Error: %s\n", strerror(res));
76 return 1;
79 /* wait for the socket to become ready for sending */
80 if(!wait_on_socket(sockfd, 0, 60000L))
82 printf("Error: timeout.\n");
83 return 1;
86 puts("Sending request.");
87 /* Send the request. Real applications should check the iolen
88 * to see if all the request has been sent */
89 res = curl_easy_send(curl, request, strlen(request), &iolen);
91 if(CURLE_OK != res)
93 printf("Error: %s\n", strerror(res));
94 return 1;
96 puts("Reading response.");
98 /* read the response */
99 for(;;)
101 char buf[1024];
103 wait_on_socket(sockfd, 1, 60000L);
104 res = curl_easy_recv(curl, buf, 1024, &iolen);
106 if(CURLE_OK != res)
107 break;
109 printf("Received %u bytes.\n", iolen);
112 /* always cleanup */
113 curl_easy_cleanup(curl);
115 return 0;