On Thu, Feb 12, 2026 at 14:36:36 +0100, Michal Prívozník wrote:
On 2/10/26 18:10, Peter Krempa wrote:
On Fri, Feb 06, 2026 at 14:52:35 +0100, Michal Privoznik via Devel wrote:
From: Michal Privoznik <mprivozn@redhat.com>
The aim of this helper is to convert subnet mask to prefix. For instance for input "255.0.0.0" to return 0. Additionally, if the input string is already a prefix (with optional leading slash character) just return that number parsed.
Signed-off-by: Michal Privoznik <mprivozn@redhat.com> --- src/libvirt_private.syms | 1 + src/util/virsocketaddr.c | 51 ++++++++++++++++++++++++++++++++++++++++ src/util/virsocketaddr.h | 2 ++ tests/sockettest.c | 29 +++++++++++++++++++++++ 4 files changed, 83 insertions(+)
[...]
+ memcpy(&in, ai->ai_addr, sizeof(in)); + prefix = __builtin_popcount(in.sin_addr.s_addr);
... so if you don't pass a mask it gives not really documented answers.
With the impl above the following predicates of the test added later are also true:
DO_TEST_SUBNET_TO_PREFIX("192.168.0.1", 6); DO_TEST_SUBNET_TO_PREFIX("129.0.0.1", 3);
Depending on the expectations either document the expectation of what happens argument isn't a subnet or add some checks
E.g. you could use __builtin_ffs to figure out the number of leading bits and then compare with __builtin_popcount to see if other bits aren't set.
Would this work on big endian machines? I mean, even on my little endian machine 255.255.255.254 is stored as 0xfeffffff. So I guess I'll just update documentation. How about:
I didn't try actually :D
* parsed and returned. There is a corner case: if @subnet is * valid IPv4 address but not valid subnet mask then a positive * value is returned, but obviously it is not valid prefix.
Documenting is fine with me. Alternatively (to the wording above) you can outline accepted strings instead, but what you wrote is okay too. Reviewed-by: Peter Krempa <pkrempa@redhat.com>