Skip to content

Instantly share code, notes, and snippets.

Created July 20, 2013 21:30
Show Gist options
  • Save xsleonard/6046486 to your computer and use it in GitHub Desktop.
Save xsleonard/6046486 to your computer and use it in GitHub Desktop.
SSL and cookie handling with libcurl
#include <stdio.h>
#include <curl/curl.h>
/* Compiling example:
* gcc -o curltest curl_ssl_cookies.c -L./lib/ -I./lib/include -lcurl -Wl,-rpath ./lib
/* Example cookie handling copied from:
* Example SSL request adapted from:
static void print_cookies(CURL *curl)
CURLcode res;
struct curl_slist *cookies;
struct curl_slist *nc;
int i;
printf("Cookies, curl knows:\n");
res = curl_easy_getinfo(curl, CURLINFO_COOKIELIST, &cookies);
if (res != CURLE_OK) {
fprintf(stderr, "Curl curl_easy_getinfo failed: %s\n", curl_easy_strerror(res));
nc = cookies, i = 1;
while (nc) {
printf("[%d]: %s\n", i, nc->data);
nc = nc->next;
if (i == 1) {
void download(const char* url, const char* cert)
CURL *curl;
CURLcode res;
curl = curl_easy_init();
if (curl)
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
// make sure to verify everything
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1L);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 2L); // yes, 2L is the correct value
curl_easy_setopt(curl, CURLOPT_SSLKEYTYPE, "PEM");
curl_easy_setopt(curl, CURLOPT_CAINFO, cert);
// if you are using OpenSSL, this option may be useful to you:
//curl_easy_setopt(curl, CURLOPT_CAPATH, "./assets/certs/");
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_COOKIEFILE, ""); /* just to start the cookie engine */
/* Perform the request, res will get the return code */
res = curl_easy_perform(curl);
/* Check for errors */
if (res != CURLE_OK)
fprintf(stderr, "curl_easy_perform() failed: %s\n",
printf("Erasing curl's knowledge of cookies!\n");
curl_easy_setopt(curl, CURLOPT_COOKIELIST, "ALL");
/* always cleanup */
int main(int argc, char* argv[])
if (argc < 3)
printf("Usage: %s <url> <pem>\n", argv[0]);
return 1;
download(argv[1], argv[2]);
return 0;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment