Created
September 7, 2022 21:28
-
-
Save michael-grunder/1387d31e7f942625fc8a88cbc58ed232 to your computer and use it in GitHub Desktop.
Hiredis SO_BINDTODEVICE example.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "hiredis.h" | |
#include <assert.h> | |
#include <sys/socket.h> | |
#include <netinet/in.h> | |
#include <linux/if.h> | |
#include <errno.h> | |
#include <string.h> | |
#include <stdlib.h> | |
char device[IFNAMSIZ]; | |
int bindToDevice(redisFD fd, void *privdata, char **user_errstr) { | |
(void)privdata; | |
if (setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, &device, sizeof(device)) != 0) { | |
*user_errstr = strerror(errno); | |
return REDIS_ERR; | |
} | |
return REDIS_OK; | |
} | |
int main(int argc, const char **argv) { | |
redisOptions opt = {0}; | |
const char *host; | |
int port; | |
redisContext *c; | |
redisReply *r; | |
if (argc > 1) { | |
strcpy(device, argv[1]); | |
} else { | |
strncpy(device, "lo", sizeof(device)); | |
} | |
host = argc > 2 ? argv[2] : "localhost"; | |
port = argc > 3 ? atoi(argv[3]) : 6379; | |
printf("Attempting to connect to %s:%d; device: %s\n", host, port, device); | |
REDIS_OPTIONS_SET_TCP(&opt, host, port); | |
REDIS_OPTIONS_SET_SOCKET_CB(&opt, bindToDevice); | |
REDIS_OPTIONS_SET_PRIVDATA(&opt, (void*)0xdeadbeef, NULL); | |
c = redisConnectWithOptions(&opt); | |
if (c == NULL || c->err) { | |
fprintf(stderr, "Failed to connect: (error: %s)\n", c->errstr); | |
exit(1); | |
} | |
r = redisCommand(c, "PING"); | |
assert(r != NULL && !c->err && r->type == REDIS_REPLY_STATUS); | |
printf("PING: %s\n", r->str); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment