From d0fd04c0a2c133f7c62a7af81a34879a3e364730 Mon Sep 17 00:00:00 2001 From: Miroslav Lichvar Date: Wed, 16 Nov 2022 15:57:46 +0100 Subject: [PATCH] util: add function for printing access subnets --- test/unit/util.c | 9 +++++++++ util.c | 20 ++++++++++++++++++++ util.h | 2 ++ 3 files changed, 31 insertions(+) diff --git a/test/unit/util.c b/test/unit/util.c index 112676d..c8bdadb 100644 --- a/test/unit/util.c +++ b/test/unit/util.c @@ -470,6 +470,15 @@ test_unit(void) s = UTI_IPSockAddrToString(&ip_saddr); TEST_CHECK(strcmp(s, "1.2.3.4:12345") == 0); + ip = ip_saddr.ip_addr; + s = UTI_IPSubnetToString(&ip, 10); + TEST_CHECK(strcmp(s, "1.2.3.4/10") == 0); + s = UTI_IPSubnetToString(&ip, 32); + TEST_CHECK(strcmp(s, "1.2.3.4") == 0); + ip.family = IPADDR_UNSPEC; + s = UTI_IPSubnetToString(&ip, 0); + TEST_CHECK(strcmp(s, "any address") == 0); + s = UTI_TimeToLogForm(2000000000); TEST_CHECK(strcmp(s, "2033-05-18 03:33:20") == 0); diff --git a/util.c b/util.c index c4c8934..064292c 100644 --- a/util.c +++ b/util.c @@ -551,6 +551,26 @@ UTI_IPSockAddrToString(const IPSockAddr *sa) /* ================================================== */ +char * +UTI_IPSubnetToString(IPAddr *subnet, int bits) +{ + char *result; + + result = NEXT_BUFFER; + + if (subnet->family == IPADDR_UNSPEC) + snprintf(result, BUFFER_LENGTH, "%s", "any address"); + else if ((subnet->family == IPADDR_INET4 && bits == 32) || + (subnet->family == IPADDR_INET6 && bits == 128)) + snprintf(result, BUFFER_LENGTH, "%s", UTI_IPToString(subnet)); + else + snprintf(result, BUFFER_LENGTH, "%s/%d", UTI_IPToString(subnet), bits); + + return result; +} + +/* ================================================== */ + char * UTI_TimeToLogForm(time_t t) { diff --git a/util.h b/util.h index a57ef9b..4655e53 100644 --- a/util.h +++ b/util.h @@ -120,6 +120,8 @@ extern int UTI_CompareIPs(const IPAddr *a, const IPAddr *b, const IPAddr *mask); extern char *UTI_IPSockAddrToString(const IPSockAddr *sa); +extern char *UTI_IPSubnetToString(IPAddr *subnet, int bits); + extern char *UTI_TimeToLogForm(time_t t); /* Adjust time following a frequency/offset change */