1
0
mirror of https://github.com/RIOT-OS/RIOT.git synced 2025-12-26 15:03:53 +01:00

sys/net/sock_util: add sock_tl_name2ep()

This commit is contained in:
Benjamin Valentin 2022-01-13 12:55:27 +01:00 committed by Benjamin Valentin
parent a2146acef7
commit 1ef6da7de4
2 changed files with 58 additions and 0 deletions

View File

@ -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
*

View File

@ -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)
{