Line data Source code
1 : /*
2 : *
3 : * Copyright (c) 2020 Project CHIP Authors
4 : * Copyright (c) 2013-2017 Nest Labs, Inc.
5 : *
6 : * Licensed under the Apache License, Version 2.0 (the "License");
7 : * you may not use this file except in compliance with the License.
8 : * You may obtain a copy of the License at
9 : *
10 : * http://www.apache.org/licenses/LICENSE-2.0
11 : *
12 : * Unless required by applicable law or agreed to in writing, software
13 : * distributed under the License is distributed on an "AS IS" BASIS,
14 : * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 : * See the License for the specific language governing permissions and
16 : * limitations under the License.
17 : */
18 :
19 : /**
20 : * @file
21 : * This file implements the concrete class
22 : * <tt>Inet::IPPrefix</tt>, which comprise two member fields:
23 : * a) a IP address and b) a length field. The CHIP Inet Layer
24 : * uses objects of this class to represent Internet protocol
25 : * address prefixes of both IPv4 and IPv6 address families.
26 : *
27 : */
28 :
29 : #include "IPPrefix.h"
30 : #include <lib/core/CHIPEncoding.h>
31 :
32 : namespace chip {
33 : namespace Inet {
34 :
35 : IPPrefix IPPrefix::Zero;
36 :
37 110 : bool IPPrefix::IsZero() const
38 : {
39 110 : return IPAddr.Addr[0] == 0 && IPAddr.Addr[1] == 0 && IPAddr.Addr[2] == 0 && IPAddr.Addr[3] == 0 && Length == 0;
40 : }
41 :
42 55 : bool IPPrefix::operator==(const IPPrefix & other) const
43 : {
44 55 : return IPAddr == other.IPAddr && Length == other.Length;
45 : }
46 :
47 55 : bool IPPrefix::operator!=(const IPPrefix & other) const
48 : {
49 55 : return IPAddr != other.IPAddr || Length != other.Length;
50 : }
51 :
52 154 : bool IPPrefix::MatchAddress(const IPAddress & addr) const
53 : {
54 154 : uint8_t l = (Length <= 128) ? Length : 128;
55 : int i;
56 :
57 298 : for (i = 0; l >= 32; i++, l = static_cast<uint8_t>(l - 32u))
58 243 : if (IPAddr.Addr[i] != addr.Addr[i])
59 99 : return false;
60 :
61 55 : if (l == 0)
62 2 : return true;
63 :
64 53 : uint32_t mask = chip::Encoding::BigEndian::HostSwap32(0xFFFFFFFF << (32 - l));
65 53 : return (IPAddr.Addr[i] & mask) == (addr.Addr[i] & mask);
66 : }
67 :
68 : } // namespace Inet
69 : } // namespace chip
|