From: Aaron Krebs Date: Wed, 30 Jul 2014 15:44:23 +0000 (+0200) Subject: Utility functions to get string representation of sockaddr components. X-Git-Url: https://git.meshlink.io/?a=commitdiff_plain;h=047eaadd44f8ce9760957b0e52833f37826544e7;p=meshlink Utility functions to get string representation of sockaddr components. --- diff --git a/src/utils.c b/src/utils.c index e45e5942..0f7b00cc 100644 --- a/src/utils.c +++ b/src/utils.c @@ -178,3 +178,51 @@ unsigned int bitfield_to_int(const void *bitfield, size_t size) { memcpy(&value, bitfield, size); return value; } + +/* Write IP address from sockaddr to string. + * Returns NULL on error. + */ +char *get_ip_str(const struct sockaddr *sa, char *s, size_t maxlen) +{ + switch(sa->sa_family) { + case AF_INET: + inet_ntop(AF_INET, &(((struct sockaddr_in *)sa)->sin_addr), + s, maxlen); + break; + + case AF_INET6: + inet_ntop(AF_INET6, &(((struct sockaddr_in6 *)sa)->sin6_addr), + s, maxlen); + break; + + default: + strncpy(s, "Unknown AF", maxlen); + return NULL; + } + + return s; +} + +/* Write port from sockaddr to string. + * Returns NULL on error. + */ +char *get_port_str(const struct sockaddr *sa, char *s, size_t maxlen) +{ + switch(sa->sa_family) { + case AF_INET: + snprintf(s, maxlen, "%d", + ntohs(((struct sockaddr_in*)sa)->sin_port)); + break; + + case AF_INET6: + snprintf(s, maxlen, "%d", + ntohs(((struct sockaddr_in6*)sa)->sin6_port)); + break; + + default: + strncpy(s, "Unknown AF", maxlen); + return NULL; + } + + return s; +} diff --git a/src/utils.h b/src/utils.h index 1ea1026a..c0b677fc 100644 --- a/src/utils.h +++ b/src/utils.h @@ -47,4 +47,7 @@ extern const char *winerror(int); extern unsigned int bitfield_to_int(const void *bitfield, size_t size); +extern char *get_ip_str(const struct sockaddr *sa, char *s, size_t maxlen); +extern char *get_port_str(const struct sockaddr *sa, char *s, size_t maxlen); + #endif /* __MESHLINK_UTILS_H__ */