MINOR: tools: Implement ipaddrcpy().
authorFrederic Lecaille <flecaille@haproxy.com>
Fri, 30 Aug 2024 11:56:15 +0000 (13:56 +0200)
committerFrederic Lecaille <flecaille@haproxy.com>
Thu, 5 Sep 2024 14:12:41 +0000 (16:12 +0200)
Implement ipaddrcpy() new function to copy only the IP address from
a sockaddr_storage struct object into a buffer.

(cherry picked from commit fb7a0922038932a6b82f1827a0214c5d2e8da32e)
Signed-off-by: Frederic Lecaille <flecaille@haproxy.com>

include/haproxy/tools.h
src/tools.c

index 937adaa..2ea9776 100644 (file)
@@ -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 <saddr> socket address data into <buf> 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[];
index b297d04..474f6e9 100644 (file)
@@ -3679,6 +3679,33 @@ struct sockaddr_storage *ipcpy(const struct sockaddr_storage *source, struct soc
        return dest;
 }
 
+/* Copy only the IP address from <saddr> socket address data into <buf> buffer.
+ * This is the responsibility of the caller to check the <buf> 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;