changeset 21097:3f83d38ba0b3

lib: Add net_ipport2str Converts struct ip_addr + port into either 127.0.0.1:6000 or [::1]:6000.
author Aki Tuomi <aki.tuomi@dovecot.fi>
date Wed, 09 Nov 2016 15:17:01 +0200
parents 95f568387300
children 968da3b58769
files src/lib/net.c src/lib/net.h
diffstat 2 files changed, 15 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- a/src/lib/net.c	Mon Nov 14 10:52:22 2016 +0200
+++ b/src/lib/net.c	Wed Nov 09 15:17:01 2016 +0200
@@ -1046,6 +1046,18 @@
 	return 0;
 }
 
+int net_ipport2str(const struct ip_addr *ip, in_port_t port, const char **str_r)
+{
+	if (!IPADDR_IS_V4(ip) && !IPADDR_IS_V6(ip)) return -1;
+
+	*str_r = t_strdup_printf("%s%s%s:%u",
+				 IPADDR_IS_V6(ip) ? "[" : "",
+				 net_ip2addr(ip),
+				 IPADDR_IS_V6(ip) ? "]" : "",
+				 port);
+	return 0;
+}
+
 int net_ipv6_mapped_ipv4_convert(const struct ip_addr *src,
 				 struct ip_addr *dest)
 {
--- a/src/lib/net.h	Mon Nov 14 10:52:22 2016 +0200
+++ b/src/lib/net.h	Wed Nov 09 15:17:01 2016 +0200
@@ -165,6 +165,9 @@
    through. */
 int net_str2hostport(const char *str, in_port_t default_port,
 		     const char **host_r, in_port_t *port_r);
+/* Converts ip and port to ipv4:port or [ipv6]:port. Returns -1 if
+   ip is not valid IPv4 or IPv6 address. */
+int net_ipport2str(const struct ip_addr *ip, in_port_t port, const char **str_r);
 
 /* Convert IPv6 mapped IPv4 address to an actual IPv4 address. Returns 0 if
    successful, -1 if the source address isn't IPv6 mapped IPv4 address. */