Skip to content

Instantly share code, notes, and snippets.

@zed

zed/check-url.c Secret

Created February 26, 2012 17:22
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 zed/cf7dd1eb3ae6e39564a5 to your computer and use it in GitHub Desktop.
Save zed/cf7dd1eb3ae6e39564a5 to your computer and use it in GitHub Desktop.
make http HEAD request in C using curl
// gcc *.c -lcurl && ./a.out http://example.com/path
#include <stdio.h>
#include <stdlib.h>
#include <curl/curl.h>
#define CHECK(setopt) do { \
CURLcode ret = (setopt); \
if (ret != CURLE_OK) { \
fputs("Failed " #setopt "\n", stderr); \
exit(ret); \
} \
} while(0)
static const long verbose = 1;
static const char *useragent = "check-url/0.0.1";
int main(int argc, char *argv[]) {
CHECK(curl_global_init(CURL_GLOBAL_ALL));
// get url to check from commmand-line
if (argc != 2) {
fprintf(stderr, "Usage: %s url\n", argv[0]);
exit(1);
}
const char *url = argv[1];
// make HEAD request
CURL *hnd = curl_easy_init();
if (hnd == NULL) {
fputs("Failed to initialize\n", stderr);
exit(2);
}
CHECK(curl_easy_setopt(hnd, CURLOPT_NOBODY, 1)); // HEAD
CHECK(curl_easy_setopt(hnd, CURLOPT_VERBOSE, verbose));
CHECK(curl_easy_setopt(hnd, CURLOPT_USERAGENT, useragent));
CHECK(curl_easy_setopt(hnd, CURLOPT_NOPROGRESS, 1));
CHECK(curl_easy_setopt(hnd, CURLOPT_FAILONERROR, 1)); //note: might fail for 401, 407
CHECK(curl_easy_setopt(hnd, CURLOPT_URL, url));
CURLcode ret = curl_easy_perform(hnd);
curl_easy_cleanup(hnd);
curl_global_cleanup();
return (int)ret; // see http://curl.haxx.se/libcurl/c/libcurl-errors.html
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment