From: Frederic Lecaille Date: Fri, 30 Aug 2024 11:56:15 +0000 (+0200) Subject: MINOR: tools: Implement ipaddrcpy(). X-Git-Tag: v3.1-dev7~31 X-Git-Url: http://git.ipfire.org/?a=commitdiff_plain;h=fb7a0922038932a6b82f1827a0214c5d2e8da32e;p=thirdparty%2Fhaproxy.git MINOR: tools: Implement ipaddrcpy(). Implement ipaddrcpy() new function to copy only the IP address from a sockaddr_storage struct object into a buffer. --- diff --git a/include/haproxy/tools.h b/include/haproxy/tools.h index fd078c7daf..5c4a81228f 100644 --- a/include/haproxy/tools.h +++ b/include/haproxy/tools.h @@ -842,6 +842,11 @@ int ipcmp2net(const struct sockaddr_storage *addr, const struct net_addr *net); */ struct sockaddr_storage *ipcpy(const struct sockaddr_storage *source, struct sockaddr_storage *dest); +/* Copy only the IP address from socket address data into buffer. * + * Return the number of bytes copied. + */ +size_t ipaddrcpy(unsigned char *buf, const struct sockaddr_storage *saddr); + char *human_time(int t, short hz_div); extern const char *monthname[]; diff --git a/src/tools.c b/src/tools.c index 39bb454e36..b0937c82b2 100644 --- a/src/tools.c +++ b/src/tools.c @@ -3685,6 +3685,33 @@ struct sockaddr_storage *ipcpy(const struct sockaddr_storage *source, struct soc return dest; } +/* Copy only the IP address from socket address data into buffer. + * This is the responsibility of the caller to check the buffer is big + * enough to contain these socket address data. + * Return the number of bytes copied. + */ +size_t ipaddrcpy(unsigned char *buf, const struct sockaddr_storage *saddr) +{ + void *addr; + unsigned char *p; + size_t addr_len; + + p = buf; + if (saddr->ss_family == AF_INET6) { + addr = &((struct sockaddr_in6 *)saddr)->sin6_addr; + addr_len = sizeof ((struct sockaddr_in6 *)saddr)->sin6_addr; + } + else { + addr = &((struct sockaddr_in *)saddr)->sin_addr; + addr_len = sizeof ((struct sockaddr_in *)saddr)->sin_addr; + } + memcpy(p, addr, addr_len); + p += addr_len; + + return p - buf; +} + + char *human_time(int t, short hz_div) { static char rv[sizeof("24855d23h")+1]; // longest of "23h59m" and "59m59s" char *p = rv;