Skip to content

Commit

Permalink
interfaces-plugin: implement netmask to prefix-length conversion
Browse files Browse the repository at this point in the history
  • Loading branch information
zinccyy committed Oct 10, 2022
1 parent aea5bc1 commit 752e271
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
31 changes: 31 additions & 0 deletions src/interfaces/src/plugin/data/interfaces/interface/ipv4/address.c
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
#include "address.h"
#include "plugin/types.h"
#include "src/utlist.h"

#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <srpc.h>

interfaces_interface_ipv4_address_element_t* interfaces_interface_ipv4_address_new(void)
{
return NULL;
Expand Down Expand Up @@ -105,3 +109,30 @@ int interfaces_interface_ipv4_address_element_set_netmask(interfaces_interface_i

return 0;
}

int interfaces_interface_ipv4_address_netmask2prefix(const char* netmask, uint8_t* prefix_length)
{
int error = 0;
struct in_addr addr = { 0 };
uint8_t prefix = 0;

// convert to bits (uint32_t -> addr.s_addr)
SRPC_SAFE_CALL_ERR_COND(error, error != 1, inet_pton(AF_INET, netmask, &addr), error_out);

// count address bits
while (addr.s_addr) {
if (addr.s_addr & 0x1) {
++prefix;
}

addr.s_addr >>= 1;
}

goto out;

error_out:
error = -1;

out:
return error;
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,10 @@ int interfaces_interface_ipv4_address_element_set_ip(interfaces_interface_ipv4_a
int interfaces_interface_ipv4_address_element_set_prefix_length(interfaces_interface_ipv4_address_element_t** el, uint8_t prefix_length);
int interfaces_interface_ipv4_address_element_set_netmask(interfaces_interface_ipv4_address_element_t** el, const char* netmask);

/*
Helper functions
*/

int interfaces_interface_ipv4_address_netmask2prefix(const char* netmask, uint8_t* prefix_length);

#endif // INTERFACES_PLUGIN_DATA_INTERFACES_INTERFACE_IPV4_ADDRESS_H

0 comments on commit 752e271

Please sign in to comment.