Skip to content

Commit

Permalink
Extract method
Browse files Browse the repository at this point in the history
  • Loading branch information
uweseimet committed Sep 25, 2023
1 parent e6c7db1 commit 8df3c69
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 15 deletions.
41 changes: 26 additions & 15 deletions cpp/devices/ctapdriver.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -177,21 +177,9 @@ bool CTapDriver::Init(const unordered_map<string, string>& const_params)
}
}
else {
string address = inet;
string netmask = "255.255.255.0"; //NOSONAR This hardcoded IP address is safe
const auto& components = Split(inet, '/', 2);
if (components.size() == 2) {
address = components[0];

int m;
if (!GetAsUnsignedInt(components[1], m) || m < 8 || m > 32) {
return cleanUp("Invalid CIDR netmask notation '" + components[1] + "'");
}

// long long is required for compatibility with 32 bit platforms
const auto mask = (long long)(pow(2, 32) - (1 << (32 - m)));
netmask = to_string((mask >> 24) & 0xff) + '.' + to_string((mask >> 16) & 0xff) + '.' +
to_string((mask >> 8) & 0xff) + '.' + to_string(mask & 0xff);
const auto [address, netmask] = ExtractAddressAndMask(inet);
if (address.empty() || netmask.empty()) {
return cleanUp("Error extracting inet address and netmask");
}

spdlog::trace("brctl addbr " + BRIDGE_NAME);
Expand Down Expand Up @@ -264,6 +252,29 @@ bool CTapDriver::Init(const unordered_map<string, string>& const_params)
#endif
}

pair<string, string> CTapDriver::ExtractAddressAndMask(const string& s) const
{
string address = s;
string netmask = "255.255.255.0"; //NOSONAR This hardcoded IP address is safe
const auto& components = Split(s, '/', 2);
if (components.size() == 2) {
address = components[0];

int m;
if (!GetAsUnsignedInt(components[1], m) || m < 8 || m > 32) {
LogErrno("Invalid CIDR netmask notation '" + components[1] + "'");
return { "", "" };
}

// long long is required for compatibility with 32 bit platforms
const auto mask = (long long)(pow(2, 32) - (1 << (32 - m)));
netmask = to_string((mask >> 24) & 0xff) + '.' + to_string((mask >> 16) & 0xff) + '.' +
to_string((mask >> 8) & 0xff) + '.' + to_string(mask & 0xff);
}

return { address, netmask };
}

string CTapDriver::IpLink(bool enable) const
{
const int fd = socket(PF_INET, SOCK_DGRAM, 0);
Expand Down
3 changes: 3 additions & 0 deletions cpp/devices/ctapdriver.h
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,9 @@ class CTapDriver
static uint32_t Crc32(span<const uint8_t>);

private:

pair<string, string> ExtractAddressAndMask(const string&) const;

array<byte, 6> m_MacAddr; // MAC Address

int m_hTAP = -1; // File handle
Expand Down

0 comments on commit 8df3c69

Please sign in to comment.