From 1ef6da7de4fdec69fbe44d8bdc28cb8acb2df2eb Mon Sep 17 00:00:00 2001 From: Benjamin Valentin Date: Thu, 13 Jan 2022 12:55:27 +0100 Subject: [PATCH] sys/net/sock_util: add sock_tl_name2ep() --- sys/include/net/sock/util.h | 16 ++++++++++++++ sys/net/sock/sock_util.c | 42 +++++++++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+) diff --git a/sys/include/net/sock/util.h b/sys/include/net/sock/util.h index 9f5336a34b..68d87d25df 100644 --- a/sys/include/net/sock/util.h +++ b/sys/include/net/sock/util.h @@ -116,6 +116,22 @@ int sock_urlsplit(const char *url, char *hostport, char *urlpath); */ int sock_tl_str2ep(struct _sock_tl_ep *ep_out, const char *str); +/** + * @brief Convert string to common IP-based transport layer endpoint + * If the `sock_dns` module is used, this will do a DNS lookup + * if @p str is not an IP address. + * + * Takes eg., "riot-os.org:1234" and converts it into the corresponding + * endpoint structure. + * + * @param[out] ep_out endpoint structure to fill + * @param[in] str string to read from + * + * @returns 0 on success + * @returns <0 otherwise + */ +int sock_tl_name2ep(struct _sock_tl_ep *ep_out, const char *str); + /** * @brief Convert string to TCP endpoint * diff --git a/sys/net/sock/sock_util.c b/sys/net/sock/sock_util.c index 1fb496a4eb..3bd760c066 100644 --- a/sys/net/sock/sock_util.c +++ b/sys/net/sock/sock_util.c @@ -28,6 +28,9 @@ #include "net/sock/udp.h" #include "net/sock/util.h" +#ifdef MODULE_SOCK_DNS +#include "net/sock/dns.h" +#endif #ifdef MODULE_FMT #include "fmt.h" @@ -254,6 +257,45 @@ int sock_tl_str2ep(struct _sock_tl_ep *ep_out, const char *str) return -EINVAL; } +int sock_tl_name2ep(struct _sock_tl_ep *ep_out, const char *str) +{ + int res = sock_tl_str2ep(ep_out, str); + if (res == 0) { + return 0; + } + +#if defined(MODULE_SOCK_DNS) + char hostbuf[CONFIG_SOCK_HOSTPORT_MAXLEN]; + const char *host; + char *hostend = strchr(str, ':'); + if (hostend == NULL) { + host = str; + ep_out->port = 0; + } else { + size_t host_len = hostend - str; + if (host_len >= sizeof(hostbuf)) { + return -EINVAL; + } + memcpy(hostbuf, str, host_len); + hostbuf[host_len] = 0; + host = hostbuf; + ep_out->port = atoi(hostend + 1);; + } + + switch (sock_dns_query(host, &ep_out->addr, AF_UNSPEC)) { + case 4: + ep_out->family = AF_INET; + return 0; + case 16: + ep_out->family = AF_INET6; + return 0; + default: + return -EINVAL; + } +#endif + return res; +} + bool sock_tl_ep_equal(const struct _sock_tl_ep *a, const struct _sock_tl_ep *b) {