Add centralized IP/Peer formatting functions

This stops us from needing to manually check against ":" to
add brackets around IPv6 addresses everywhere.
This commit is contained in:
Matt Stancliff 2014-10-23 12:40:02 -04:00
parent 3cd36a4dd9
commit 2d90619f88
4 changed files with 37 additions and 0 deletions

View File

@ -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);
}

View File

@ -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

View File

@ -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 <stdio.h>
#include "testhelp.h"

View File

@ -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);