From 90a2cfbc5487ad328dfb3f7e3ab6a81a0cc8f3f7 Mon Sep 17 00:00:00 2001 From: rofl0r Date: Sat, 2 Jan 2016 10:35:41 +0000 Subject: [PATCH] network.c: simplify get_ip_string() fixes warnings "cast increases required alignment of target type" closes #3 --- src/network.c | 33 +++++++++------------------------ src/network.h | 2 +- 2 files changed, 10 insertions(+), 25 deletions(-) diff --git a/src/network.c b/src/network.c index 9caef04..7cda1d1 100644 --- a/src/network.c +++ b/src/network.c @@ -249,35 +249,20 @@ CLEANUP: * Convert the network address into either a dotted-decimal or an IPv6 * hex string. */ -char *get_ip_string (struct sockaddr *sa, char *buf, size_t buflen) +const char *get_ip_string (struct sockaddr *sa, char *buf, size_t buflen) { + int af; + void* addr; assert (sa != NULL); assert (buf != NULL); assert (buflen != 0); buf[0] = '\0'; /* start with an empty string */ - - switch (sa->sa_family) { - case AF_INET: - { - struct sockaddr_in *sa_in = (struct sockaddr_in *) sa; - - inet_ntop (AF_INET, &sa_in->sin_addr, buf, buflen); - break; - } - case AF_INET6: - { - struct sockaddr_in6 *sa_in6 = - (struct sockaddr_in6 *) sa; - - inet_ntop (AF_INET6, &sa_in6->sin6_addr, buf, buflen); - break; - } - default: - /* no valid family */ - return NULL; - } - - return buf; + af = sa->sa_family; + if(af != AF_INET && af != AF_INET6) return NULL; + addr = (af == AF_INET ? + (void*)&(((struct sockaddr_in *) (void*)sa)->sin_addr) : + (void*)&(((struct sockaddr_in6 *) (void*)sa)->sin6_addr) ); + return inet_ntop(af, addr, buf, buflen); } /* diff --git a/src/network.h b/src/network.h index b6ddaa6..15af481 100644 --- a/src/network.h +++ b/src/network.h @@ -27,7 +27,7 @@ extern ssize_t safe_read (int fd, char *buffer, size_t count); extern int write_message (int fd, const char *fmt, ...); extern ssize_t readline (int fd, char **whole_buffer); -extern char *get_ip_string (struct sockaddr *sa, char *buf, size_t len); +extern const char *get_ip_string (struct sockaddr *sa, char *buf, size_t len); extern int full_inet_pton (const char *ip, void *dst); #endif