Skip to content

Instantly share code, notes, and snippets.

@anthann
Last active January 22, 2019 07:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anthann/a0f21eea02a57b5f53f9551f49cc1017 to your computer and use it in GitHub Desktop.
Save anthann/a0f21eea02a57b5f53f9551f49cc1017 to your computer and use it in GitHub Desktop.
Do `curl -X GET -I www.example.com` with liburl
#include <stdlib.h>
#include <string.h>
#include "libcurl_demo.h"
struct string {
char *ptr;
size_t len;
};
void init_string(struct string *s) {
s->len = 0;
s->ptr = malloc(s->len+1);
if (s->ptr == NULL) {
fprintf(stderr, "malloc() failed\n");
exit(EXIT_FAILURE);
}
s->ptr[0] = '\0';
}
size_t writefunc(void *ptr, size_t size, size_t nmemb, struct string *s) {
size_t new_len = s->len + size*nmemb;
s->ptr = realloc(s->ptr, new_len+1);
if (s->ptr == NULL) {
fprintf(stderr, "realloc() failed\n");
exit(EXIT_FAILURE);
}
memcpy(s->ptr+s->len, ptr, size*nmemb);
s->ptr[new_len] = '\0';
s->len = new_len;
return size*nmemb;
}
CURLcode getUrlHeader(char *url) {
CURL *curl;
CURLcode res = CURLE_OK;
curl = curl_easy_init();
if (curl) {
struct string s;
init_string(&s);
curl_easy_setopt(curl, CURLOPT_URL,url);
// Line below will change HTTP Method to "HEAD".
curl_easy_setopt(curl, CURLOPT_NOBODY, 1L);
curl_easy_setopt(curl, CURLOPT_HEADER, 1L);
// Force to set HTTP Method to "GET"
curl_easy_setopt(curl, CURLOPT_HTTPGET, 1L);
// curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "GET");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writefunc);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &s);
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
printf("%s\n", s.ptr);
free(s.ptr);
}
return res;
}
#import "curl.h"
CURLcode getUrlHeader(char *url);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment