net/ipv4: Ipv4_address_prefix::prefix_matches

The new method checks whether a given IPv4 address matches the IPv4
address prefix.

Ref #2139
This commit is contained in:
Martin Stein 2016-10-17 13:11:02 +02:00 committed by Christian Helmuth
parent 6276daecab
commit da925b9cd7
2 changed files with 22 additions and 4 deletions

View File

@ -218,6 +218,8 @@ struct Net::Ipv4_address_prefix
bool valid() const { return address.valid(); }
void print(Genode::Output &output) const;
bool prefix_matches(Ipv4_address const &ip) const;
};

View File

@ -16,19 +16,20 @@
#include <net/ipv4.h>
using namespace Genode;
using namespace Net;
struct Scanner_policy_number
{
static bool identifier_char(char c, unsigned i ) {
return Genode::is_digit(c) && c !='.'; }
static bool identifier_char(char c, unsigned i ) {
return Genode::is_digit(c) && c !='.'; }
};
typedef ::Genode::Token<Scanner_policy_number> Token;
Ipv4_address Ipv4_packet::ip_from_string(const char *ip)
{
using Token = ::Genode::Token<Scanner_policy_number>;
Ipv4_address ip_addr;
Token t(ip);
char tmpstr[4];
@ -86,3 +87,18 @@ void Ipv4_address_prefix::print(Genode::Output &output) const
{
Genode::print(output, address, "/", prefix);
}
bool Ipv4_address_prefix::prefix_matches(Ipv4_address const &ip) const
{
uint8_t prefix_left = prefix;
uint8_t byte = 0;
for (; prefix_left >= 8; prefix_left -= 8, byte++) {
if (ip.addr[byte] != address.addr[byte]) {
return false; }
}
if (prefix_left == 0) {
return true; }
uint8_t const mask = ~(0xff >> prefix_left);
return !((ip.addr[byte] ^ address.addr[byte]) & mask);
}