Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
H

hiredis

> 编程语言
Open source

Minimalistic C client for Redis >= 1.2

6.7K stars0 likes2 views
WebsiteGitHub

About

Minimalistic C client for Redis >= 1.2

This Readme reflects the latest changed in the master branch. See v1.0.0 for the Readme and documentation for the latest release (API/ABI history).

HIREDIS

Hiredis is a minimalistic C client library for the Redis database.

It is minimalistic because it just adds minimal support for the protocol, but at the same time it uses a high level printf-alike API in order to make it much higher level than otherwise suggested by its minimal code base and the lack of explicit bindings for every Redis command.

Apart from supporting sending commands and receiving replies, it comes with a reply parser that is decoupled from the I/O layer. It is a stream parser designed for easy reusability, which can for instance be used in higher level language bindings for efficient reply parsing.

Hiredis only supports the binary-safe Redis protocol, so you can use it with any Redis version >= 1.2.0.

The library comes with multiple APIs. There is the synchronous API, the asynchronous API and the reply parsing API.

Upgrading to > 1.2.0 (PRERELEASE)

  • After v1.2.0 we modified how we invoke poll(2) to wait for connections to complete, such that we will now retry the call if it is interrupted by a signal until:

    a) The connection succeeds or fails. b) The overall connection timeout is reached.

    In previous versions, an interrupted poll(2) call would cause the connection to fail with c->err set to REDIS_ERR_IO and c->errstr set to poll(2): Interrupted system call.

Upgrading to 1.1.0

Almost all users will simply need to recompile their applications against the newer version of hiredis.

NOTE: Hiredis can now return nan in addition to -inf and inf in a REDIS_REPLY_DOUBLE. Applications that deal with RESP3 doubles should make sure to account for this.

Upgrading to 1.0.2

NOTE: v1.0.1 erroneously bumped SONAME, which is why it is skipped here.

Version 1.0.2 is simply 1.0.0 with a fix for CVE-2021-32765. They are otherwise identical.

Upgrading to 1.0.0

Version 1.0.0 marks the first stable release of Hiredis. It includes some minor breaking changes, mostly to make the exposed API more uniform and self-explanatory. It also bundles the updated sds library, to sync up with upstream and Redis. For code changes see the Changelog.

Note: As described below, a few member names have been changed but most applications should be able to upgrade with minor code changes and recompiling.

IMPORTANT: Breaking changes from 0.14.1 -> 1.0.0

  • redisContext has two additional members (free_privdata, and privctx).
  • redisOptions.timeout has been renamed to redisOptions.connect_timeout, and we've added redisOptions.command_timeout.
  • redisReplyObjectFunctions.createArray now takes size_t instead of int for its length parameter.

IMPORTANT: Breaking changes when upgrading from 0.13.x -> 0.14.x

Bulk and multi-bulk lengths less than -1 or greater than LLONG_MAX are now protocol errors. This is consistent with the RESP specification. On 32-bit platforms, the upper bound is lowered to SIZE_MAX.

Change redisReply.len to size_t, as it denotes the the size of a string

User code should compare this to size_t values as well. If it was used to compare to other values, casting might be necessary or can be removed, if casting was applied before.

Upgrading from <0.9.0

Version 0.9.0 is a major overhaul of hiredis in every aspect. However, upgrading existing code using hiredis should not be a big pain. The key thing to keep in mind when upgrading is that hiredis >= 0.9.0 uses a redisContext* to keep state, in contrast to the stateless 0.0.1 that only has a file descriptor to work with.

Synchronous API

To consume the synchronous API, there are only a few function calls that need to be introduced:

c
redisContext *redisConnect(const char *ip, int port);
void *redisCommand(redisContext *c, const char *format, ...);
void freeReplyObject(void *reply);

Connecting

The function redisConnect is used to create a so-called redisContext. The context is where Hiredis holds state for a connection. The redisContext struct has an integer err field that is non-zero when the connection is in an error state. The field errstr will contain a string with a description of the error. More information on errors can be found in the Errors section. After trying to connect to Redis using redisConnect you should check the err field to see if establishing the connection was successful:

c
redisContext *c = redisConnect("127.0.0.1", 6379);
if (c == NULL || c->err) {
    if (c) {
        printf("Error: %s\n", c->errstr);
        // handle error
    } else {
        printf("Can't allocate redis context\n");
    }
}

One can also use redisConnectWithOptions which takes a redisOptions argument that can be configured with endpoint information as well as many different flags to change how the redisContext will be configured.

c
redisOptions opt = {0};

/* One can set the endpoint with one of our helper macros */
if (tcp) {
    REDIS_OPTIONS_SET_TCP(&opt, "localhost", 6379);
} else {
    REDIS_OPTIONS_SET_UNIX(&opt, "/tmp/redis.sock");
}

/* And privdata can be specified with another helper */
REDIS_OPTIONS_SET_PRIVDATA(&opt, myPrivData, myPrivDataDtor);

/* Finally various options may be set via the `options` member, as described below */
opt->options |= REDIS_OPT_PREFER_IPV4;

If a connection is lost, int redisReconnect(redisContext *c) can be used to restore the connection using the same endpoint and options as the given context.

Configurable redisOptions flags

There are several flags you may set in the redisOptions struct to change default behavior. You can specify the flags via the redisOptions->options member.

Flag Description
REDIS_OPT_NONBLOCK Tells hiredis to make a non-blocking connection.
REDIS_OPT_REUSEADDR Tells hiredis to set the SO_REUSEADDR socket option
REDIS_OPT_PREFER_IPV4
REDIS_OPT_PREFER_IPV6
REDIS_OPT_PREFER_IP_UNSPEC
Informs hiredis to either prefer IPv4 or IPv6 when invoking getaddrinfo. REDIS_OPT_PREFER_IP_UNSPEC will cause hiredis to specify AF_UNSPEC in the getaddrinfo call, which means both IPv4 and IPv6 addresses will be searched simultaneously.
Hiredis prefers IPv4 by default.
REDIS_OPT_NO_PUSH_AUTOFREE Tells hiredis to not install the default RESP3 PUSH handler (which just intercepts and frees the replies). This is useful in situations where you want to process these messages in-band.
REDIS_OPT_NOAUTOFREEREPLIES ASYNC: tells hiredis not to automatically invoke freeReplyObject after executing the reply callback.
REDIS_OPT_NOAUTOFREE ASYNC: Tells hiredis not to automatically free the redisAsyncContext on connection/communication failure, but only if the user makes an explicit call to redisAsyncDisconnect or redisAsyncFree

Note: A redisContext is not thread-safe.

Other configuration using socket options

The following socket options are applied directly to the underlying socket. The values are not stored in the redisContext, so they are not automatically applied when reconnecting using redisReconnect(). These functions return REDIS_OK on success. On failure, REDIS_ERR is returned and the underlying connection is closed.

To configure these for an asynchronous context (see Asynchronous API below), use ac->c to get the redisContext out of an asyncRedisContext.

c
int redisEnableKeepAlive(redisContext *c);
int redisEnableKeepAliveWithInterval(redisContext *c, int interval);

Enables TCP keepalive by setting the following socket options (with some variations depending on OS):

  • SO_KEEPALIVE;
  • TCP_KEEPALIVE or TCP_KEEPIDLE, value configurable using the interval parameter, default 15 seconds;
  • TCP_KEEPINTVL set to 1/3 of interval;
  • TCP_KEEPCNT set to 3.
c
int redisSetTcpUserTimeout(redisContext *c, unsigned int timeout);

Set the TCP_USER_TIMEOUT Linux-specific socket option which is as described in the tcp man page:

When the value is greater than 0, it specifies the maximum amount of time in milliseconds that trans mitted data may remain unacknowledged before TCP will forcibly close the corresponding connection and return ETIMEDOUT to the application. If the option value is specified as 0, TCP will use the system default.

Sending commands

There are several ways to issue commands to Redis. The first that will be introduced is redisCommand. This function takes a format similar to printf. In the simplest form, it is used like this:

c
reply = redisCommand(context, "SET foo bar");

The specifier %s interpolates a string in the command, and uses strlen to determine the length of the string:

c
reply = redisCommand(context, "SET foo %s", value);

When you need to pass binary safe strings in a command, the %b specifier can be used. Together with a pointer to the string, it requires a size_t length argument of the string:

c
reply = redisCommand(context, "SET foo %b", value, (size_t) valuelen);

Internally, Hiredis splits the command in different arguments and will convert it to the protocol used to communicate with Redis. One or more spaces separates arguments, so you can use the specifiers anywhere in an argument:

c
reply = redisCommand(context, "SET key:%s %s", myid, value);

Using replies

The return value of redisCommand holds a reply when the command was successfully executed. When an error occurs, the return value is NULL and the err field in the context will be set (see section on Errors). Once an error is returned the context cannot be reused and you should set up a new connection.

The standard replies that redisCommand are of the type redisReply. The type field in the redisReply should be used to test what kind of reply was received:

RESP2

  • REDIS_REPLY_STATUS:

    • The command replied with a status reply. The status string can be accessed using reply->str. The length of this string can be accessed using reply->len.
  • REDIS_REPLY_ERROR:

    • The command replied with an error. The error string can be accessed identical to REDIS_REPLY_STATUS.
  • REDIS_REPLY_INTEGER:

    • The command replied with an integer. The integer value can be accessed using the reply->integer field of type long long.
  • REDIS_REPLY_NIL:

    • The command replied with a nil object. There is no data to access.
  • REDIS_REPLY_STRING:

    • A bulk (string) reply. The value of the reply can be accessed using reply->str. The length of this string can be accessed using reply->len.
  • REDIS_REPLY_ARRAY:

    • A multi bulk reply. The number of elements in the multi bulk reply is stored in reply->elements. Every element in the multi bulk reply is a redisReply object as well and can be accessed via reply->element[..index..]. Redis may reply with nested arrays but this is fully supported.

RESP3

Hiredis also supports every new RESP3 data type which are as follows. For more information about the protocol see the RESP3 specification.

  • REDIS_REPLY_DOUBLE:

    • The command replied with a double-precision floating point number. The value is stored as a string in the str member, and can be converted with strtod or similar.
  • REDIS_REPLY_BOOL:

    • A boolean true/false reply. The value is stored

Issues· 86 open

View all issuesOpen on GitHub
  • #1373

    Large bulk-string replies (e.g. CLIENT LIST with many connected clients) require the entire reply in memory before any of it can be consumed

    Updated Sep 13, 2026
  • #1358

    [Bug]Signed integer overflow in processBulkItem bytelen += len+2 on a RESP bulk length of LLONG_MAX (CWE-190)

    Updated Aug 31, 2026
  • #1357

    [Bug]Unbounded memory allocation in RESP aggregate parsing: a single untrusted MAP/ARRAY header triggers OOM (CWE-770 / CWE-789)

    Updated Aug 28, 2026
  • #1363

    WINDOWS_EXPORT_ALL_SYMBOLS in CMakeLists.txt leads to linker errors in client programs

    Updated Aug 28, 2026
  • #1361

    `redisConnectUnix`: `strncpy` of `sun_path` omits the NUL when the path length is `sizeof(sun_path)-1` or more

    Updated Aug 28, 2026
  • #1359

    Async pub/sub: RESP3 PUSH with fewer than 3 elements heap-buffer-overflows in `__redisGetSubscribeCallback`

    Updated Aug 28, 2026
  • #1333

    [SECURITY] Integer truncation in processBulkItem on LLP64 (Windows x64) treats incomplete bulk as complete

    Updated Jul 22, 2026
  • #1059

    Support for non blocking SSL handshake

    Updated Jun 8, 2026
  • #1320

    redisAsyncDisconnect closes the socket immediately without waiting for replies when RESP3 + SUBSCRIBE is used

    Updated Dec 31, 2025
  • #1319

    [BUG] libhiredis_ssl missing link to libhiredis on non-Windows platforms

    Updated Dec 13, 2025

> Tags

C

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 23, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言