]> git.ipfire.org Git - thirdparty/haproxy.git/commitdiff
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>
Fri, 30 Aug 2024 15:04:09 +0000 (17:04 +0200)
Implement ipaddrcpy() new function to copy only the IP address from
a sockaddr_storage struct object into a buffer.

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

index fd078c7daf8d0dff973a593fc376863469f59a76..5c4a81228f20d5565f6a26c2cc0865f1c04f8951 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 39bb454e367152564f58a961a2ad1400db06c76d..b0937c82b2698c102562f42f59d35523e882cc77 100644 (file)
@@ -3685,6 +3685,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;