Skip to content

Commit e2954e0

Browse files
libpolycube: adds new method to the utils library
- split_ip_and_prefix Signed-off-by: Francesco Messina <francescomessina92@hotmail.com>
1 parent 515b518 commit e2954e0

2 files changed

Lines changed: 24 additions & 3 deletions

File tree

src/libs/polycube/include/polycube/services/utils.h

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,12 @@ uint32_t get_netmask_length(const std::string &netmask_string);
6565

6666
/* Take in ingress a prefix length like 24 and return the
6767
* "netmask" -> 255.255.255.0 in this case */
68-
std::string get_netmask_from_CIDR(const int cidr);
68+
std::string get_netmask_from_prefixlength(const int prefixlength);
69+
70+
/* Take in ingress an ip/prefix and return the ip address and the netmask
71+
* in the variables ip_address and netmask passed by reference */
72+
void split_ip_and_prefix(const std::string &ip_and_prefix,
73+
std::string &ip_address, std::string &netmask);
6974

7075
/*
7176
* formats a debug string, custom specifiers are evaluated by a

src/libs/polycube/src/utils.cpp

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -296,17 +296,33 @@ uint32_t get_netmask_length(const std::string &netmask_string) {
296296
throw std::runtime_error("IP Address is not in a valid format");
297297
}
298298

299-
std::string get_netmask_from_CIDR(const int cidr) {
299+
std::string get_netmask_from_prefixlength(const int prefixlength) {
300300
uint32_t ipv4Netmask;
301301

302+
if (prefixlength == 0) {
303+
return "0.0.0.0";
304+
}
305+
302306
ipv4Netmask = 0xFFFFFFFF;
303-
ipv4Netmask <<= 32 - cidr;
307+
ipv4Netmask <<= 32 - prefixlength;
304308
ipv4Netmask = ntohl(ipv4Netmask);
305309
struct in_addr addr = {ipv4Netmask};
306310

307311
return inet_ntoa(addr);
308312
}
309313

314+
void split_ip_and_prefix(const std::string &ip_and_prefix,
315+
std::string &ip_address, std::string &netmask) {
316+
// ip_and_prefix = ip_address/prefix
317+
std::istringstream split(ip_and_prefix);
318+
std::vector<std::string> info;
319+
char split_char = '/';
320+
for (std::string each; std::getline(split, each, split_char);
321+
info.push_back(each));
322+
ip_address = info[0];
323+
netmask = get_netmask_from_prefixlength(std::atoi(info[1].c_str()));
324+
}
325+
310326
} // namespace utils
311327
} // namespace service
312328
} // namespace polycube

0 commit comments

Comments
 (0)