1
0
Fork 0

Codechange: use std::string_view for NetworkAddress::IsInNetmask of std::string

pull/14048/head
Rubidium 2025-04-20 11:19:56 +02:00 committed by rubidium42
parent ff2da0fc73
commit a0e4dab771
2 changed files with 9 additions and 14 deletions

View File

@ -12,6 +12,7 @@
#include "address.h" #include "address.h"
#include "../network_internal.h" #include "../network_internal.h"
#include "../../debug.h" #include "../../debug.h"
#include "../../core/string_consumer.hpp"
#include "../../safeguards.h" #include "../../safeguards.h"
@ -143,31 +144,25 @@ bool NetworkAddress::IsFamily(int family)
* @note netmask without /n assumes all bits need to match. * @note netmask without /n assumes all bits need to match.
* @return true if this IP is within the netmask. * @return true if this IP is within the netmask.
*/ */
bool NetworkAddress::IsInNetmask(const std::string &netmask) bool NetworkAddress::IsInNetmask(std::string_view netmask)
{ {
/* Resolve it if we didn't do it already */ /* Resolve it if we didn't do it already */
if (!this->IsResolved()) this->GetAddress(); if (!this->IsResolved()) this->GetAddress();
int cidr = this->address.ss_family == AF_INET ? 32 : 128; int cidr = this->address.ss_family == AF_INET ? 32 : 128;
NetworkAddress mask_address; StringConsumer consumer{netmask};
/* Check for CIDR separator */ /* Check for CIDR separator */
auto cidr_separator_location = netmask.find('/'); NetworkAddress mask_address(consumer.ReadUntilChar('/', StringConsumer::SKIP_ONE_SEPARATOR), 0, this->address.ss_family);
if (cidr_separator_location != std::string::npos) { if (mask_address.GetAddressLength() == 0) return false;
int tmp_cidr = atoi(netmask.substr(cidr_separator_location + 1).c_str());
if (consumer.AnyBytesLeft()) {
int tmp_cidr = consumer.ReadIntegerBase(10, cidr);
/* Invalid CIDR, treat as single host */ /* Invalid CIDR, treat as single host */
if (tmp_cidr > 0 && tmp_cidr < cidr) cidr = tmp_cidr; if (tmp_cidr > 0 && tmp_cidr < cidr) cidr = tmp_cidr;
/* Remove the / so that NetworkAddress works on the IP portion */
mask_address = NetworkAddress(netmask.substr(0, cidr_separator_location), 0, this->address.ss_family);
} else {
mask_address = NetworkAddress(netmask, 0, this->address.ss_family);
} }
if (mask_address.GetAddressLength() == 0) return false;
uint32_t *ip; uint32_t *ip;
uint32_t *mask; uint32_t *mask;
switch (this->address.ss_family) { switch (this->address.ss_family) {

View File

@ -115,7 +115,7 @@ public:
} }
bool IsFamily(int family); bool IsFamily(int family);
bool IsInNetmask(const std::string &netmask); bool IsInNetmask(std::string_view netmask);
/** /**
* Compare the address of this class with the address of another. * Compare the address of this class with the address of another.