View Javadoc
1   /*
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2026, QOS.ch. All rights reserved.
4    *
5    * This program and the accompanying materials are dual-licensed under
6    * either the terms of the Eclipse Public License v2.0 as published by
7    * the Eclipse Foundation
8    *
9    *   or (per the licensee's choosing)
10   *
11   * under the terms of the GNU Lesser General Public License version 2.1
12   * as published by the Free Software Foundation.
13   */
14  package ch.qos.logback.core.util;
15  
16  import java.net.InetAddress;
17  import java.net.UnknownHostException;
18  
19  /**
20   * Matches an {@link InetAddress} against a single IP address or a CIDR network
21   * range.
22   * <p>
23   * Accepted forms:
24   * <ul>
25   * <li>Single address: {@code 192.168.1.10}, {@code 2001:db8::1}</li>
26   * <li>CIDR range: {@code 192.168.1.0/24}, {@code 2001:db8::/32}</li>
27   * </ul>
28   *
29   * @author Ceki G&uuml;lc&uuml;
30   * @since 1.6.2
31   */
32  public class IpAddressMatcher {
33  
34      private final String original;
35      private final byte[] networkAddress;
36      private final int prefixLength;
37  
38      /**
39       * Creates a matcher for the given address or CIDR specification.
40       *
41       * @param addressOrCidr a single IP or {@code address/prefixLength}
42       * @throws IllegalArgumentException if the specification is invalid
43       */
44      public IpAddressMatcher(String addressOrCidr) {
45          if (addressOrCidr == null) {
46              throw new IllegalArgumentException("addressOrCidr must not be null");
47          }
48          this.original = addressOrCidr.trim();
49          if (this.original.isEmpty()) {
50              throw new IllegalArgumentException("addressOrCidr must not be empty");
51          }
52  
53          String addressPart;
54          Integer explicitPrefix = null;
55          int slashIndex = this.original.indexOf('/');
56          if (slashIndex >= 0) {
57              addressPart = this.original.substring(0, slashIndex).trim();
58              String prefixPart = this.original.substring(slashIndex + 1).trim();
59              if (addressPart.isEmpty() || prefixPart.isEmpty()) {
60                  throw new IllegalArgumentException("Invalid CIDR specification [" + addressOrCidr + "]");
61              }
62              try {
63                  explicitPrefix = Integer.parseInt(prefixPart);
64              } catch (NumberFormatException e) {
65                  throw new IllegalArgumentException(
66                          "Invalid prefix length in [" + addressOrCidr + "]", e);
67              }
68          } else {
69              addressPart = this.original;
70          }
71  
72          InetAddress parsed;
73          try {
74              parsed = InetAddress.getByName(addressPart);
75          } catch (UnknownHostException e) {
76              throw new IllegalArgumentException("Unknown host or invalid IP address [" + addressPart + "]", e);
77          }
78  
79          this.networkAddress = parsed.getAddress();
80          int maxPrefix = this.networkAddress.length * 8;
81          if (explicitPrefix != null) {
82              if (explicitPrefix < 0 || explicitPrefix > maxPrefix) {
83                  throw new IllegalArgumentException("Prefix length " + explicitPrefix
84                          + " is out of range for address [" + addressPart + "] (0-" + maxPrefix + ")");
85              }
86              this.prefixLength = explicitPrefix;
87          } else {
88              this.prefixLength = maxPrefix;
89          }
90      }
91  
92      /**
93       * Returns {@code true} if the given address matches this matcher.
94       *
95       * @param address the address to test; may be {@code null}
96       * @return {@code true} if {@code address} matches
97       */
98      public boolean matches(InetAddress address) {
99          if (address == null) {
100             return false;
101         }
102         return matchesBytes(address.getAddress());
103     }
104 
105     /**
106      * Returns {@code true} if the given address string matches this matcher.
107      *
108      * @param address an IP address string
109      * @return {@code true} if the address matches
110      * @throws IllegalArgumentException if {@code address} cannot be parsed
111      */
112     public boolean matches(String address) {
113         if (address == null) {
114             throw new IllegalArgumentException("address must not be null");
115         }
116         try {
117             return matches(InetAddress.getByName(address.trim()));
118         } catch (UnknownHostException e) {
119             throw new IllegalArgumentException("Unknown host or invalid IP address [" + address + "]", e);
120         }
121     }
122 
123     private boolean matchesBytes(byte[] candidate) {
124         if (candidate == null || candidate.length != networkAddress.length) {
125             return false;
126         }
127 
128         int fullBytes = prefixLength / 8;
129         int remainingBits = prefixLength % 8;
130 
131         for (int i = 0; i < fullBytes; i++) {
132             if (candidate[i] != networkAddress[i]) {
133                 return false;
134             }
135         }
136 
137         if (remainingBits > 0) {
138             int mask = 0xFF << (8 - remainingBits);
139             if ((candidate[fullBytes] & mask) != (networkAddress[fullBytes] & mask)) {
140                 return false;
141             }
142         }
143 
144         return true;
145     }
146 
147     /**
148      * The original specification used to construct this matcher.
149      */
150     public String getSpecification() {
151         return original;
152     }
153 
154     @Override
155     public String toString() {
156         return "IpAddressMatcher[" + original + "]";
157     }
158 }