1 /*
2 * Copyright (c) 2019 Linaro Limited
3 *
4 * SPDX-License-Identifier: Apache-2.0
5 */
6
7 #ifdef CONFIG_NET_SOCKETS
8
9 #include <zephyr/net/socketutils.h>
10
net_addr_str_find_port(const char * addr_str)11 const char *net_addr_str_find_port(const char *addr_str)
12 {
13 const char *p = strrchr(addr_str, ':');
14
15 if (p == NULL) {
16 return NULL;
17 }
18
19 /* If it's not IPv6 numeric notation, we guaranteedly got a port */
20 if (*addr_str != '[') {
21 return p + 1;
22 }
23
24 /* IPv6 numeric address, and ':' preceded by ']' */
25 if (p[-1] == ']') {
26 return p + 1;
27 }
28
29 /* Otherwise, just raw IPv6 address, ':' is component separator */
30 return NULL;
31 }
32
net_getaddrinfo_addr_str(const char * addr_str,const char * def_port,const struct zsock_addrinfo * hints,struct zsock_addrinfo ** res)33 int net_getaddrinfo_addr_str(const char *addr_str, const char *def_port,
34 const struct zsock_addrinfo *hints,
35 struct zsock_addrinfo **res)
36 {
37 const char *port;
38 char host[NI_MAXHOST];
39
40 if (addr_str == NULL) {
41 errno = EINVAL;
42 return -1;
43 }
44
45 port = net_addr_str_find_port(addr_str);
46
47 if (port == NULL) {
48 port = def_port;
49 } else {
50 int host_len = port - addr_str - 1;
51
52 if (host_len > sizeof(host) - 1) {
53 errno = EINVAL;
54 return -1;
55 }
56 strncpy(host, addr_str, host_len + 1);
57 host[host_len] = '\0';
58 addr_str = host;
59 }
60
61 return zsock_getaddrinfo(addr_str, port, hints, res);
62 }
63
64 #endif
65