anetPeerToString() refactoring and more explicit checks.

Related to PR #2010.
This commit is contained in:
antirez 2014-09-18 17:22:19 +02:00
parent 6d699ea401
commit 6d53b2f34b

View File

@ -529,12 +529,9 @@ int anetPeerToString(int fd, char *ip, size_t ip_len, int *port) {
struct sockaddr_storage sa;
socklen_t salen = sizeof(sa);
if (getpeername(fd,(struct sockaddr*)&sa,&salen) == -1) {
if (port) *port = 0;
ip[0] = '?';
ip[1] = '\0';
return -1;
}
if (getpeername(fd,(struct sockaddr*)&sa,&salen) == -1) goto error;
if (ip_len == 0) goto error;
if (sa.ss_family == AF_INET) {
struct sockaddr_in *s = (struct sockaddr_in *)&sa;
if (ip) inet_ntop(AF_INET,(void*)&(s->sin_addr),ip,ip_len);
@ -543,11 +540,25 @@ int anetPeerToString(int fd, char *ip, size_t ip_len, int *port) {
struct sockaddr_in6 *s = (struct sockaddr_in6 *)&sa;
if (ip) inet_ntop(AF_INET6,(void*)&(s->sin6_addr),ip,ip_len);
if (port) *port = ntohs(s->sin6_port);
} else {
if (ip) ip[0] = '\0';
} else if (sa.ss_family == AF_UNIX) {
if (ip) strncpy(ip,"unixsocket",ip_len);
if (port) *port = 0;
} else {
goto error;
}
return 0;
error:
if (ip) {
if (ip_len >= 2) {
ip[0] = '?';
ip[1] = '\0';
} else if (ip_len == 1) {
ip[0] = '\0';
}
}
if (port) *port = 0;
return -1;
}
int anetSockName(int fd, char *ip, size_t ip_len, int *port) {