xref: /curl/docs/examples/sendrecv.c (revision 45202cbb)
1 /***************************************************************************
2  *                                  _   _ ____  _
3  *  Project                     ___| | | |  _ \| |
4  *                             / __| | | | |_) | |
5  *                            | (__| |_| |  _ <| |___
6  *                             \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
9  *
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 https://curl.se/docs/copyright.html.
13  *
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.
17  *
18  * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19  * KIND, either express or implied.
20  *
21  * SPDX-License-Identifier: curl
22  *
23  ***************************************************************************/
24 /* <DESC>
25  * Demonstrate curl_easy_send() and curl_easy_recv() usage.
26  * </DESC>
27  */
28 
29 #include <stdio.h>
30 #include <string.h>
31 #include <curl/curl.h>
32 
33 /* Auxiliary function that waits on the socket. */
wait_on_socket(curl_socket_t sockfd,int for_recv,long timeout_ms)34 static int wait_on_socket(curl_socket_t sockfd, int for_recv, long timeout_ms)
35 {
36   struct timeval tv;
37   fd_set infd, outfd, errfd;
38   int res;
39 
40   tv.tv_sec = timeout_ms / 1000;
41   tv.tv_usec = (int)(timeout_ms % 1000) * 1000;
42 
43   FD_ZERO(&infd);
44   FD_ZERO(&outfd);
45   FD_ZERO(&errfd);
46 
47 /* Avoid this warning with pre-2020 Cygwin/MSYS releases:
48  * warning: conversion to 'long unsigned int' from 'curl_socket_t' {aka 'int'}
49  * may change the sign of the result [-Wsign-conversion]
50  */
51 #if defined(__GNUC__)
52 #pragma GCC diagnostic push
53 #pragma GCC diagnostic ignored "-Wsign-conversion"
54 #elif defined(_MSC_VER)
55 #pragma warning(push)
56 #pragma warning(disable:4127)  /* conditional expression is constant */
57 #endif
58   FD_SET(sockfd, &errfd); /* always check for error */
59 
60   if(for_recv) {
61     FD_SET(sockfd, &infd);
62   }
63   else {
64     FD_SET(sockfd, &outfd);
65   }
66 #if defined(__GNUC__)
67 #pragma GCC diagnostic pop
68 #elif defined(_MSC_VER)
69 #pragma warning(pop)
70 #endif
71 
72   /* select() returns the number of signalled sockets or -1 */
73   res = select((int)sockfd + 1, &infd, &outfd, &errfd, &tv);
74   return res;
75 }
76 
main(void)77 int main(void)
78 {
79   CURL *curl;
80   /* Minimalistic http request */
81   const char *request = "GET / HTTP/1.0\r\nHost: example.com\r\n\r\n";
82   size_t request_len = strlen(request);
83 
84   /* A general note of caution here: if you are using curl_easy_recv() or
85      curl_easy_send() to implement HTTP or _any_ other protocol libcurl
86      supports "natively", you are doing it wrong and you should stop.
87 
88      This example uses HTTP only to show how to use this API, it does not
89      suggest that writing an application doing this is sensible.
90   */
91 
92   curl = curl_easy_init();
93   if(curl) {
94     CURLcode res;
95     curl_socket_t sockfd;
96     size_t nsent_total = 0;
97 
98     curl_easy_setopt(curl, CURLOPT_URL, "https://example.com");
99     /* Do not do the transfer - only connect to host */
100     curl_easy_setopt(curl, CURLOPT_CONNECT_ONLY, 1L);
101     res = curl_easy_perform(curl);
102 
103     if(res != CURLE_OK) {
104       printf("Error: %s\n", curl_easy_strerror(res));
105       return 1;
106     }
107 
108     /* Extract the socket from the curl handle - we need it for waiting. */
109     res = curl_easy_getinfo(curl, CURLINFO_ACTIVESOCKET, &sockfd);
110 
111     if(res != CURLE_OK) {
112       printf("Error: %s\n", curl_easy_strerror(res));
113       return 1;
114     }
115 
116     printf("Sending request.\n");
117 
118     do {
119       /* Warning: This example program may loop indefinitely.
120        * A production-quality program must define a timeout and exit this loop
121        * as soon as the timeout has expired. */
122       size_t nsent;
123       do {
124         nsent = 0;
125         res = curl_easy_send(curl, request + nsent_total,
126             request_len - nsent_total, &nsent);
127         nsent_total += nsent;
128 
129         if(res == CURLE_AGAIN && !wait_on_socket(sockfd, 0, 60000L)) {
130           printf("Error: timeout.\n");
131           return 1;
132         }
133       } while(res == CURLE_AGAIN);
134 
135       if(res != CURLE_OK) {
136         printf("Error: %s\n", curl_easy_strerror(res));
137         return 1;
138       }
139 
140       printf("Sent %lu bytes.\n", (unsigned long)nsent);
141 
142     } while(nsent_total < request_len);
143 
144     printf("Reading response.\n");
145 
146     for(;;) {
147       /* Warning: This example program may loop indefinitely (see above). */
148       char buf[1024];
149       size_t nread;
150       do {
151         nread = 0;
152         res = curl_easy_recv(curl, buf, sizeof(buf), &nread);
153 
154         if(res == CURLE_AGAIN && !wait_on_socket(sockfd, 1, 60000L)) {
155           printf("Error: timeout.\n");
156           return 1;
157         }
158       } while(res == CURLE_AGAIN);
159 
160       if(res != CURLE_OK) {
161         printf("Error: %s\n", curl_easy_strerror(res));
162         break;
163       }
164 
165       if(nread == 0) {
166         /* end of the response */
167         break;
168       }
169 
170       printf("Received %lu bytes.\n", (unsigned long)nread);
171     }
172 
173     /* always cleanup */
174     curl_easy_cleanup(curl);
175   }
176   return 0;
177 }
178