Skip to content

Instantly share code, notes, and snippets.

@FooBarWidget
Created August 27, 2014 21:53
Show Gist options
  • Save FooBarWidget/5ecd22c737b5da570c11 to your computer and use it in GitHub Desktop.
Save FooBarWidget/5ecd22c737b5da570c11 to your computer and use it in GitHub Desktop.
#include <curl/curl.h>
#include <stdio.h>
#include <string.h>
#include <string>
#ifndef CURLINFO_RESPONSE_CODE
#define CURLINFO_RESPONSE_CODE CURLINFO_HTTP_CODE
#endif
std::string responseData;
static size_t
curlDataReceived(void *buffer, size_t size, size_t nmemb, void *userData) {
responseData.append((const char *) buffer, size * nmemb);
return size * nmemb;
}
int
main(int argc, char *argv[]) {
if (argc > 1 && strcmp(argv[1], "--test-fix") == 0) {
printf("Initializing libcurl\n");
curl_global_init(CURL_GLOBAL_ALL);
}
CURL *curl = curl_easy_init();
char lastErrorMessage[CURL_ERROR_SIZE];
curl_easy_setopt(curl, CURLOPT_URL, "http://169.254.169.254/latest/meta-data/instance-type");
curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 15);
curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, lastErrorMessage);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curlDataReceived);
CURLcode code = curl_easy_perform(curl);
curl_easy_cleanup(curl);
if (code == 0) {
long responseCode;
if (curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &responseCode) != CURLE_OK) {
printf("Cannot not autodetect Amazon instance type (internal error: could "
"not query libcurl response code). Assuming this is not an Amazon instance\n");
return false;
}
if (responseCode != 200) {
printf("Cannot not autodetect Amazon instance type (HTTP error: response "
"code %ld; body \"%s\"). Assuming this is not an Amazon instance\n",
responseCode, responseData.c_str());
return false;
}
if (responseData.empty()) {
printf("Cannot not autodetect Amazon instance type (HTTP error: the server "
"returned an empty response). Assuming this is not an Amazon instance\n");
return false;
}
printf("Autodetected Amazon instance type: %s\n", responseData.c_str());
return true;
} else {
printf("Cannot contact Amazon metadata server\n");
return false;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment