base: add nm_dhcp_iaid_{from,to}_hexstr() helpers

This commit is contained in:
Thomas Haller 2023-02-20 16:17:55 +01:00
parent 69106d0aef
commit 4c18adbc74
No known key found for this signature in database
GPG key ID: 29C2366E4DFC5728
3 changed files with 67 additions and 0 deletions

View file

@ -9,3 +9,33 @@
NM_CACHED_QUARK_FCN("nm-crypto-error-quark", _nm_crypto_error_quark);
/*****************************************************************************/
char *
nm_dhcp_iaid_to_hexstr(guint32 iaid, char buf[static NM_DHCP_IAID_TO_HEXSTR_BUF_LEN])
{
iaid = htobe32(iaid);
return nm_utils_bin2hexstr_full(&iaid, sizeof(iaid), ':', FALSE, buf);
}
gboolean
nm_dhcp_iaid_from_hexstr(const char *str, guint32 *out_value)
{
union {
guint32 num;
guint8 bin[sizeof(guint32)];
} iaid;
if (!nm_utils_hexstr2bin_full(str,
TRUE,
FALSE,
FALSE,
":",
sizeof(iaid),
iaid.bin,
sizeof(iaid),
NULL))
return FALSE;
NM_SET_OUT(out_value, be32toh(iaid.num));
return TRUE;
}

View file

@ -423,4 +423,12 @@ typedef enum {
NM_DNS_IP_CONFIG_TYPE_VPN,
} NMDnsIPConfigType;
/*****************************************************************************/
#define NM_DHCP_IAID_TO_HEXSTR_BUF_LEN (3 * sizeof(guint32))
char *nm_dhcp_iaid_to_hexstr(guint32 iaid, char buf[static NM_DHCP_IAID_TO_HEXSTR_BUF_LEN]);
gboolean nm_dhcp_iaid_from_hexstr(const char *str, guint32 *out_value);
#endif /* __NM_LIBNM_BASE_H__ */

View file

@ -11352,6 +11352,34 @@ test_dnsname(void)
/*****************************************************************************/
static void
test_dhcp_iaid_hexstr(void)
{
char str[NM_DHCP_IAID_TO_HEXSTR_BUF_LEN];
int i;
for (i = 0; i < 10; i++) {
guint32 iaid = nmtst_get_rand_uint32();
guint32 iaid2;
char *s;
gboolean r;
s = nm_dhcp_iaid_to_hexstr(iaid, str);
g_assert(s == str);
g_assert(strlen(s) < sizeof(str));
r = nm_dhcp_iaid_from_hexstr(str, &iaid2);
g_assert(r);
g_assert_cmpint(iaid, ==, iaid2);
}
g_assert_cmpstr(nm_dhcp_iaid_to_hexstr(0, str), ==, "00:00:00:00");
g_assert_cmpstr(nm_dhcp_iaid_to_hexstr(1, str), ==, "00:00:00:01");
g_assert_cmpstr(nm_dhcp_iaid_to_hexstr(0x01002044, str), ==, "01:00:20:44");
}
/*****************************************************************************/
NMTST_DEFINE();
int
@ -11699,6 +11727,7 @@ main(int argc, char **argv)
g_test_add_func("/core/general/test_direct_string_is_refstr", test_direct_string_is_refstr);
g_test_add_func("/core/general/test_connection_path", test_connection_path);
g_test_add_func("/core/general/test_dnsname", test_dnsname);
g_test_add_func("/core/general/test_dhcp_iaid_hexstr", test_dhcp_iaid_hexstr);
return g_test_run();
}