1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 1998 - 2012, Daniel Stenberg, <daniel@haxx.se>, et al.
10 * This software is licensed as described in the file COPYING, which
11 * you should have received as part of this distribution. The terms
12 * are also available at http://curl.haxx.se/docs/copyright.html.
14 * You may opt to use, copy, modify, merge, publish, distribute and/or sell
15 * copies of the Software, and permit persons to whom the Software is
16 * furnished to do so, under the terms of the COPYING file.
18 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19 * KIND, either express or implied.
21 ***************************************************************************/
22 /* An example of curl_easy_send() and curl_easy_recv() usage. */
26 #include <curl/curl.h>
28 /* Auxiliary function that waits on the socket. */
29 static int wait_on_socket(curl_socket_t sockfd, int for_recv, long timeout_ms)
32 fd_set infd, outfd, errfd;
35 tv.tv_sec = timeout_ms / 1000;
36 tv.tv_usec= (timeout_ms % 1000) * 1000;
42 FD_SET(sockfd, &errfd); /* always check for error */
46 FD_SET(sockfd, &infd);
50 FD_SET(sockfd, &outfd);
53 /* select() returns the number of signalled sockets or -1 */
54 res = select(sockfd + 1, &infd, &outfd, &errfd, &tv);
62 /* Minimalistic http request */
63 const char *request = "GET / HTTP/1.0\r\nHost: example.com\r\n\r\n";
64 curl_socket_t sockfd; /* socket */
69 curl = curl_easy_init();
71 curl_easy_setopt(curl, CURLOPT_URL, "http://example.com");
72 /* Do not do the transfer - only connect to host */
73 curl_easy_setopt(curl, CURLOPT_CONNECT_ONLY, 1L);
74 res = curl_easy_perform(curl);
78 printf("Error: %s\n", strerror(res));
82 /* Extract the socket from the curl handle - we'll need it for waiting.
83 * Note that this API takes a pointer to a 'long' while we use
84 * curl_socket_t for sockets otherwise.
86 res = curl_easy_getinfo(curl, CURLINFO_LASTSOCKET, &sockextr);
90 printf("Error: %s\n", curl_easy_strerror(res));
96 /* wait for the socket to become ready for sending */
97 if(!wait_on_socket(sockfd, 0, 60000L))
99 printf("Error: timeout.\n");
103 puts("Sending request.");
104 /* Send the request. Real applications should check the iolen
105 * to see if all the request has been sent */
106 res = curl_easy_send(curl, request, strlen(request), &iolen);
110 printf("Error: %s\n", curl_easy_strerror(res));
113 puts("Reading response.");
115 /* read the response */
120 wait_on_socket(sockfd, 1, 60000L);
121 res = curl_easy_recv(curl, buf, 1024, &iolen);
126 nread = (curl_off_t)iolen;
128 printf("Received %" CURL_FORMAT_CURL_OFF_T " bytes.\n", nread);
132 curl_easy_cleanup(curl);