xref: /third_party/curl/docs/examples/sendrecv.c (revision 13498266)
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. */
34static 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__) && defined(__CYGWIN__)
52#pragma GCC diagnostic push
53#pragma GCC diagnostic ignored "-Wsign-conversion"
54#endif
55  FD_SET(sockfd, &errfd); /* always check for error */
56
57  if(for_recv) {
58    FD_SET(sockfd, &infd);
59  }
60  else {
61    FD_SET(sockfd, &outfd);
62  }
63#if defined(__GNUC__) && defined(__CYGWIN__)
64#pragma GCC diagnostic pop
65#endif
66
67  /* select() returns the number of signalled sockets or -1 */
68  res = select((int)sockfd + 1, &infd, &outfd, &errfd, &tv);
69  return res;
70}
71
72int main(void)
73{
74  CURL *curl;
75  /* Minimalistic http request */
76  const char *request = "GET / HTTP/1.0\r\nHost: example.com\r\n\r\n";
77  size_t request_len = strlen(request);
78
79  /* A general note of caution here: if you are using curl_easy_recv() or
80     curl_easy_send() to implement HTTP or _any_ other protocol libcurl
81     supports "natively", you are doing it wrong and you should stop.
82
83     This example uses HTTP only to show how to use this API, it does not
84     suggest that writing an application doing this is sensible.
85  */
86
87  curl = curl_easy_init();
88  if(curl) {
89    CURLcode res;
90    curl_socket_t sockfd;
91    size_t nsent_total = 0;
92
93    curl_easy_setopt(curl, CURLOPT_URL, "https://example.com");
94    /* Do not do the transfer - only connect to host */
95    curl_easy_setopt(curl, CURLOPT_CONNECT_ONLY, 1L);
96    res = curl_easy_perform(curl);
97
98    if(res != CURLE_OK) {
99      printf("Error: %s\n", curl_easy_strerror(res));
100      return 1;
101    }
102
103    /* Extract the socket from the curl handle - we will need it for
104       waiting. */
105    res = curl_easy_getinfo(curl, CURLINFO_ACTIVESOCKET, &sockfd);
106
107    if(res != CURLE_OK) {
108      printf("Error: %s\n", curl_easy_strerror(res));
109      return 1;
110    }
111
112    printf("Sending request.\n");
113
114    do {
115      /* Warning: This example program may loop indefinitely.
116       * A production-quality program must define a timeout and exit this loop
117       * as soon as the timeout has expired. */
118      size_t nsent;
119      do {
120        nsent = 0;
121        res = curl_easy_send(curl, request + nsent_total,
122            request_len - nsent_total, &nsent);
123        nsent_total += nsent;
124
125        if(res == CURLE_AGAIN && !wait_on_socket(sockfd, 0, 60000L)) {
126          printf("Error: timeout.\n");
127          return 1;
128        }
129      } while(res == CURLE_AGAIN);
130
131      if(res != CURLE_OK) {
132        printf("Error: %s\n", curl_easy_strerror(res));
133        return 1;
134      }
135
136      printf("Sent %lu bytes.\n", (unsigned long)nsent);
137
138    } while(nsent_total < request_len);
139
140    printf("Reading response.\n");
141
142    for(;;) {
143      /* Warning: This example program may loop indefinitely (see above). */
144      char buf[1024];
145      size_t nread;
146      do {
147        nread = 0;
148        res = curl_easy_recv(curl, buf, sizeof(buf), &nread);
149
150        if(res == CURLE_AGAIN && !wait_on_socket(sockfd, 1, 60000L)) {
151          printf("Error: timeout.\n");
152          return 1;
153        }
154      } while(res == CURLE_AGAIN);
155
156      if(res != CURLE_OK) {
157        printf("Error: %s\n", curl_easy_strerror(res));
158        break;
159      }
160
161      if(nread == 0) {
162        /* end of the response */
163        break;
164      }
165
166      printf("Received %lu bytes.\n", (unsigned long)nread);
167    }
168
169    /* always cleanup */
170    curl_easy_cleanup(curl);
171  }
172  return 0;
173}
174