From 2d90619f88b81d1a094a875d73f8afd244480730 Mon Sep 17 00:00:00 2001 From: Matt Stancliff Date: Thu, 23 Oct 2014 12:40:02 -0400 Subject: [PATCH] Add centralized IP/Peer formatting functions This stops us from needing to manually check against ":" to add brackets around IPv6 addresses everywhere. --- src/anet.c | 24 ++++++++++++++++++++++++ src/anet.h | 3 +++ src/sds.c | 9 +++++++++ src/sds.h | 1 + 4 files changed, 37 insertions(+) diff --git a/src/anet.c b/src/anet.c index 1e5d85495..3e39751d7 100644 --- a/src/anet.c +++ b/src/anet.c @@ -589,6 +589,22 @@ error: return -1; } +int anetFormatIP(char *fmt, size_t fmt_len, char *ip, int port) { + if (port >= 0) + return snprintf(fmt,fmt_len, + strchr(ip,':') ? "[%s]:%d" : "%s:%d", ip, port); + else + return snprintf(fmt, fmt_len, strchr(ip,':') ? "[%s]" : "%s", ip); +} + +int anetFormatPeer(int fd, char *fmt, size_t fmt_len) { + char ip[INET6_ADDRSTRLEN]; + int port; + + anetPeerToString(fd,ip,sizeof(ip),&port); + return anetFormatIP(fmt, fmt_len, ip, port); +} + int anetSockName(int fd, char *ip, size_t ip_len, int *port) { struct sockaddr_storage sa; socklen_t salen = sizeof(sa); @@ -610,3 +626,11 @@ int anetSockName(int fd, char *ip, size_t ip_len, int *port) { } return 0; } + +int anetFormatSock(int fd, char *fmt, size_t fmt_len) { + char ip[INET6_ADDRSTRLEN]; + int port; + + anetSockName(fd,ip,sizeof(ip),&port); + return anetFormatIP(fmt, fmt_len, ip, port); +} diff --git a/src/anet.h b/src/anet.h index b94a0cd17..846758073 100644 --- a/src/anet.h +++ b/src/anet.h @@ -70,5 +70,8 @@ int anetSendTimeout(char *err, int fd, long long ms); int anetPeerToString(int fd, char *ip, size_t ip_len, int *port); int anetKeepAlive(char *err, int fd, int interval); int anetSockName(int fd, char *ip, size_t ip_len, int *port); +int anetFormatIP(char *fmt, size_t fmt_len, char *ip, int port); +int anetFormatPeer(int fd, char *fmt, size_t fmt_len); +int anetFormatSock(int fd, char *fmt, size_t fmt_len); #endif diff --git a/src/sds.c b/src/sds.c index 1df1043ed..fa71896ef 100644 --- a/src/sds.c +++ b/src/sds.c @@ -962,6 +962,15 @@ sds sdsjoin(char **argv, int argc, char *sep) { return join; } +sds sdsformatip(char *ip, int port) { + if (port >= 0) + return sdscatfmt(sdsempty(), + strchr(ip,':') ? "[%s]:%i" : "%s:%i", ip, port); + else + return sdscatfmt(sdsempty(), + strchr(ip,':') ? "[%s]" : "%s", ip); +} + #ifdef SDS_TEST_MAIN #include #include "testhelp.h" diff --git a/src/sds.h b/src/sds.h index 37aaf7a28..f1f84c812 100644 --- a/src/sds.h +++ b/src/sds.h @@ -91,6 +91,7 @@ sds sdscatrepr(sds s, const char *p, size_t len); sds *sdssplitargs(const char *line, int *argc); sds sdsmapchars(sds s, const char *from, const char *to, size_t setlen); sds sdsjoin(char **argv, int argc, char *sep); +sds sdsformatip(char *ip, int port); /* Low level functions exposed to the user API */ sds sdsMakeRoomFor(sds s, size_t addlen);