C captcha solver: an API client with libcurl

A C captcha solver is a program that posts a challenge to a solver API over HTTPS and reads the answer, here with libcurl as its only dependency. With ilovecaptcha it makes two calls, createTask then getTaskResult. Since the C standard library has neither JSON nor base64, the example writes both by hand. This page explains each part and gives the complete file.

Updated on · Written and maintained by the ilovecaptcha team

Preview: the API described here is in public beta. Endpoint names, fields and codes can still change until the end of the beta, and no API key is distributed yet.

How do you call a captcha solver API from C?

With libcurl and its easy interface. The function post writes the JSON body into a buffer, starting with clientKey, then sets CURLOPT_URL, CURLOPT_HTTPHEADER, CURLOPT_POSTFIELDS and a CURLOPT_TIMEOUT of 30 seconds with curl_easy_setopt. The callback on_data appends each chunk of the reply to a growing buffer, which post returns as a string.

The C example at a glance
Item Value
Language level C99
Dependency libcurl
File solve.c
Build and run gcc solve.c -o solve -lcurl && ./solve
Install libcurl libcurl4-openssl-dev, or vcpkg install curl

How do you send the captcha image and wait for the answer in C?

The image is read with fread into a buffer and encoded by the function base64, written in the file because the C standard library has none. solve posts the task to createTask, extracts taskId, then calls getTaskResult after each pause until status is ready.

  • POLL_MS is 1500: the macro sleep_ms maps to Sleep on Windows and to usleep elsewhere.
  • TIMEOUT_SECONDS is 120, measured with time.
  • field reads one value of the reply, object returns the solution object by counting braces.
  • Every string these functions return is allocated with malloc: the caller releases it.

How do you handle the API key and errors in C?

The key is the macro API_KEY, pasted into the body at compile time. To keep it out of the source, read it with getenv from a variable such as ILOVECAPTCHA_KEY and pass it to snprintf in its place. The example treats every failure as fatal: a libcurl error prints curl_easy_strerror and exits with code 1, a non-zero errorId prints errorCode and errorDescription and exits with code 1, and a task still not ready after the deadline exits with code 2.

What does a complete C captcha solver client look like?

The file below is the whole client, in 188 lines, most of them spent on what other languages provide: a growing buffer, two JSON readers and a base64 encoder. main reads captcha.png, submits it as an aws-waf task and prints the solution. Replace YOUR_API_KEY and YOUR_API_URL with your own values, then build the file with the command shown above.

solve.c · Complete C client: one createTask call, then getTaskResult until the task is ready (preview format).
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <curl/curl.h>
#ifdef _WIN32
#include <windows.h>
#define sleep_ms(ms) Sleep(ms)
#else
#include <unistd.h>
#define sleep_ms(ms) usleep((ms) * 1000)
#endif

#define API_KEY "YOUR_API_KEY"
#define BASE_URL "YOUR_API_URL"
#define POLL_MS 1500
#define TIMEOUT_SECONDS 120

struct buffer {
    char *data;
    size_t size;
};

static size_t on_data(void *chunk, size_t size, size_t count, void *userdata) {
    struct buffer *buf = userdata;
    size_t total = size * count;
    char *grown = realloc(buf->data, buf->size + total + 1);
    if (!grown) return 0;
    buf->data = grown;
    memcpy(buf->data + buf->size, chunk, total);
    buf->size += total;
    buf->data[buf->size] = '\0';
    return total;
}

static char *field(const char *json, const char *name) {
    char key[64];
    snprintf(key, sizeof key, "\"%s\"", name);
    const char *p = strstr(json, key);
    if (!p) return NULL;
    p = strchr(p + strlen(key), ':');
    if (!p) return NULL;
    p++;
    while (*p == ' ') p++;
    const char *end;
    if (*p == '"') {
        p++;
        end = strchr(p, '"');
    } else {
        end = p + strcspn(p, ",} \n");
    }
    if (!end) return NULL;
    char *value = malloc(end - p + 1);
    memcpy(value, p, end - p);
    value[end - p] = '\0';
    return value;
}

static char *object(const char *json, const char *name) {
    char key[64];
    snprintf(key, sizeof key, "\"%s\"", name);
    const char *start = strstr(json, key);
    if (!start) return NULL;
    start = strchr(start, '{');
    if (!start) return NULL;
    int depth = 0;
    for (const char *p = start; *p; p++) {
        if (*p == '{') depth++;
        if (*p == '}' && --depth == 0) {
            char *value = malloc(p - start + 2);
            memcpy(value, start, p - start + 1);
            value[p - start + 1] = '\0';
            return value;
        }
    }
    return NULL;
}

static char *post(const char *route, const char *fields) {
    char url[256];
    snprintf(url, sizeof url, "%s%s", BASE_URL, route);
    size_t len = strlen(fields) + strlen(API_KEY) + 32;
    char *body = malloc(len);
    snprintf(body, len, "{\"clientKey\":\"%s\"%s%s}", API_KEY, *fields ? "," : "", fields);
    struct buffer buf = {NULL, 0};
    CURL *curl = curl_easy_init();
    struct curl_slist *headers = curl_slist_append(NULL, "Content-Type: application/json");
    curl_easy_setopt(curl, CURLOPT_URL, url);
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, body);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, on_data);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &buf);
    curl_easy_setopt(curl, CURLOPT_TIMEOUT, 30L);
    CURLcode code = curl_easy_perform(curl);
    curl_slist_free_all(headers);
    curl_easy_cleanup(curl);
    free(body);
    if (code != CURLE_OK) {
        fprintf(stderr, "%s\n", curl_easy_strerror(code));
        exit(1);
    }
    char *error_id = field(buf.data, "errorId");
    if (error_id && strcmp(error_id, "0") != 0) {
        char *error_code = field(buf.data, "errorCode");
        char *description = field(buf.data, "errorDescription");
        fprintf(stderr, "%s: %s\n", error_code ? error_code : "?", description ? description : "");
        exit(1);
    }
    free(error_id);
    return buf.data;
}

static char *solve(const char *task_json) {
    size_t len = strlen(task_json) + 16;
    char *fields = malloc(len);
    snprintf(fields, len, "\"task\":%s", task_json);
    char *result = post("/createTask", fields);
    free(fields);
    char *status = field(result, "status");
    if (status && strcmp(status, "ready") == 0) {
        free(status);
        return object(result, "solution");
    }
    free(status);
    char *task_id = field(result, "taskId");
    free(result);
    time_t deadline = time(NULL) + TIMEOUT_SECONDS;
    char poll[64];
    snprintf(poll, sizeof poll, "\"taskId\":%s", task_id);
    while (time(NULL) < deadline) {
        sleep_ms(POLL_MS);
        result = post("/getTaskResult", poll);
        status = field(result, "status");
        if (status && strcmp(status, "ready") == 0) {
            free(status);
            return object(result, "solution");
        }
        free(status);
        free(result);
    }
    fprintf(stderr, "task %s not ready after %d s\n", task_id, TIMEOUT_SECONDS);
    exit(2);
}

static char *base64(const unsigned char *data, size_t size) {
    static const char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    char *out = malloc((size + 2) / 3 * 4 + 1);
    size_t o = 0;
    for (size_t i = 0; i < size; i += 3) {
        unsigned v = data[i] << 16;
        if (i + 1 < size) v |= data[i + 1] << 8;
        if (i + 2 < size) v |= data[i + 2];
        out[o++] = table[(v >> 18) & 63];
        out[o++] = table[(v >> 12) & 63];
        out[o++] = i + 1 < size ? table[(v >> 6) & 63] : '=';
        out[o++] = i + 2 < size ? table[v & 63] : '=';
    }
    out[o] = '\0';
    return out;
}

int main(void) {
    FILE *file = fopen("captcha.png", "rb");
    if (!file) {
        perror("captcha.png");
        return 1;
    }
    fseek(file, 0, SEEK_END);
    long size = ftell(file);
    rewind(file);
    unsigned char *data = malloc(size);
    fread(data, 1, size, file);
    fclose(file);
    char *image = base64(data, size);
    free(data);
    size_t len = strlen(image) + 64;
    char *task = malloc(len);
    snprintf(task, len, "{\"type\":\"aws-waf\",\"image\":\"%s\"}", image);
    free(image);
    curl_global_init(CURL_GLOBAL_DEFAULT);
    char *solution = solve(task);
    printf("%s\n", solution ? solution : "(no solution)");
    char *result = post("/getBalance", "");
    char *balance = field(result, "balance");
    printf("%s\n", balance ? balance : "?");
    curl_global_cleanup();
    return 0;
}

C captcha solver: frequently asked questions

Do I need an SDK to solve captchas in C?

No SDK, and a single library: libcurl, for the HTTPS transport. Everything else is in the file, written against the C99 standard library: the JSON body is assembled with snprintf, the reply is read by two short functions, the image is encoded by a short base64 function. The file on this page is the complete client, to compile with your program or to split into a header and a source file.

Does the C example build on Windows?

Yes, with a libcurl built for your compiler, for instance through vcpkg install curl. The source already handles the one platform difference it has: the pause between two polls calls Sleep from windows.h on Windows and usleep from unistd.h elsewhere, behind the macro sleep_ms. With the Microsoft compiler, link against the import library of libcurl instead of passing the -lcurl option.

What does solve return in C, and how do you read it?

A string allocated with malloc that holds the solution object as JSON text, or NULL when the reply has none. The example prints it. To read a value, apply the function field of the example to that string with the name you expect: token for a token widget, offset for a slider, text for characters to type. An array such as points needs a real JSON parser, for instance cJSON or Jansson.

Sources

The facts and figures quoted on this page come from these sources.