diff --git a/include/public/net.h b/include/public/net.h new file mode 100644 index 0000000..4ef21bc --- /dev/null +++ b/include/public/net.h @@ -0,0 +1,33 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +#pragma once + +#include + +#include "str.h" + +enum { + TLSL_L3PROTO_IPV4, + TLSL_L3PROTO_IPV6, +}; + +struct tlsl_ipv4_addr { + uint32_t addr; +}; + +struct tlsl_ipv6_addr { + uint8_t addr[16]; +}; + +struct tlsl_ip_addr { + union { + struct tlsl_ipv4_addr v4; + struct tlsl_ipv6_addr v6; + }; + uint8_t l3proto; +}; + +int tlsl_ip_addr_parse(const char *s, struct tlsl_ip_addr *out); +str_buf_t tlsl_ip_addr_fmt(const struct tlsl_ip_addr *a); diff --git a/meson.build b/meson.build index dcbcc82..651d4b6 100644 --- a/meson.build +++ b/meson.build @@ -36,9 +36,10 @@ eventloop_info = { }[platform_info['eventloop']] sources = [ - 'src/str.c', - 'src/eventloop.c', 'src/array_list.c', + 'src/eventloop.c', + 'src/net.c', + 'src/str.c', eventloop_info['path'], ] diff --git a/src/net.c b/src/net.c new file mode 100644 index 0000000..6d00560 --- /dev/null +++ b/src/net.c @@ -0,0 +1,41 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +#include +#include + +#include "export.h" +#include "public/net.h" + +EXPORT int tlsl_ip_addr_parse(const char *s, struct tlsl_ip_addr *out) { + if (inet_pton(AF_INET, s, &out->v4) == 1) { + out->l3proto = TLSL_L3PROTO_IPV4; + return 0; + } + if (inet_pton(AF_INET6, s, &out->v6) == 1) { + out->l3proto = TLSL_L3PROTO_IPV6; + return 0; + } + return 1; +} + +EXPORT str_buf_t tlsl_ip_addr_fmt(const struct tlsl_ip_addr *a) { + char buf[INET6_ADDRSTRLEN] = { 0 }; + const char *res; + + switch (a->l3proto) { + case TLSL_L3PROTO_IPV4: + res = inet_ntop(AF_INET, &a->v4, buf, sizeof(buf)); + break; + case TLSL_L3PROTO_IPV6: + res = inet_ntop(AF_INET6, &a->v6, buf, sizeof(buf)); + break; + default: + errno = EINVAL; + return SBUF_NULL; + } + if (!res) + return SBUF_NULL; + return sbuf_from_sview(sview_from_cstr_unbounded(buf)); +}