From 6d406473341758ca02e6ba77d8cfbdf1303a0469 Mon Sep 17 00:00:00 2001 From: Con Kolivas Date: Fri, 28 Nov 2014 00:24:58 +1100 Subject: [PATCH] Add a helper function for converting a struct sockaddr into a url and port --- src/libckpool.c | 25 +++++++++++++++++++++++++ src/libckpool.h | 1 + 2 files changed, 26 insertions(+) diff --git a/src/libckpool.c b/src/libckpool.c index 860b537e..499e66be 100644 --- a/src/libckpool.c +++ b/src/libckpool.c @@ -30,6 +30,7 @@ #include #include #include +#include #include "libckpool.h" #include "sha2.h" @@ -406,6 +407,30 @@ bool extract_sockaddr(char *url, char **sockaddr_url, char **sockaddr_port) return true; } +/* Convert a sockaddr structure into a url and port. URL should be a string of + * INET6_ADDRSTRLEN size */ +bool url_from_sockaddr(const struct sockaddr *addr, char *url, int *port_no) +{ + switch(addr->sa_family) { + const struct sockaddr_in *inet4_in; + const struct sockaddr_in6 *inet6_in; + + case AF_INET: + inet4_in = (struct sockaddr_in *)url; + inet_ntop(AF_INET, &inet4_in->sin_addr, url, INET6_ADDRSTRLEN); + *port_no = htons(inet4_in->sin_port); + break; + case AF_INET6: + inet6_in = (struct sockaddr_in6 *)url; + inet_ntop(AF_INET6, &inet6_in->sin6_addr, url, INET6_ADDRSTRLEN); + *port_no = htons(inet6_in->sin6_port); + break; + default: + return false; + } + return true; +} + void keep_sockalive(int fd) { const int tcp_one = 1; diff --git a/src/libckpool.h b/src/libckpool.h index b6d3c8f7..fba59562 100644 --- a/src/libckpool.h +++ b/src/libckpool.h @@ -422,6 +422,7 @@ static inline bool sock_timeout(void) } bool extract_sockaddr(char *url, char **sockaddr_url, char **sockaddr_port); +bool url_from_sockaddr(const struct sockaddr *addr, char *url, int *port_no); void keep_sockalive(int fd); void nolinger_socket(int fd); void noblock_socket(int fd);