blob: 26a504a29c1cf7cbeb4713def7a49154ed6d2c1f [file] [log] [blame]
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001/*
2 * Copyright 2017 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.net;
18
19import android.annotation.IntDef;
20import android.annotation.NonNull;
21import android.annotation.Nullable;
22import android.compat.annotation.UnsupportedAppUsage;
23import android.net.wifi.WifiInfo;
24import android.os.Build;
25import android.os.Parcel;
26import android.os.Parcelable;
27
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090028import com.android.net.module.util.MacAddressUtils;
29
30import java.lang.annotation.Retention;
31import java.lang.annotation.RetentionPolicy;
32import java.net.Inet6Address;
33import java.net.UnknownHostException;
34import java.security.SecureRandom;
35import java.util.Arrays;
Remi NGUYEN VAN28028e52021-03-15 07:31:54 +000036import java.util.Objects;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090037
38/**
39 * Representation of a MAC address.
40 *
41 * This class only supports 48 bits long addresses and does not support 64 bits long addresses.
42 * Instances of this class are immutable. This class provides implementations of hashCode()
43 * and equals() that make it suitable for use as keys in standard implementations of
44 * {@link java.util.Map}.
45 */
46public final class MacAddress implements Parcelable {
47
48 private static final int ETHER_ADDR_LEN = 6;
49 private static final byte[] ETHER_ADDR_BROADCAST = addr(0xff, 0xff, 0xff, 0xff, 0xff, 0xff);
50
51 /**
52 * The MacAddress representing the unique broadcast MAC address.
53 */
54 public static final MacAddress BROADCAST_ADDRESS = MacAddress.fromBytes(ETHER_ADDR_BROADCAST);
55
56 /**
57 * The MacAddress zero MAC address.
58 *
59 * <p>Not publicly exposed or treated specially since the OUI 00:00:00 is registered.
60 * @hide
61 */
62 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
63 public static final MacAddress ALL_ZEROS_ADDRESS = new MacAddress(0);
64
65 /** @hide */
66 @Retention(RetentionPolicy.SOURCE)
67 @IntDef(prefix = { "TYPE_" }, value = {
68 TYPE_UNKNOWN,
69 TYPE_UNICAST,
70 TYPE_MULTICAST,
71 TYPE_BROADCAST,
72 })
73 public @interface MacAddressType { }
74
75 /** @hide Indicates a MAC address of unknown type. */
76 public static final int TYPE_UNKNOWN = 0;
77 /** Indicates a MAC address is a unicast address. */
78 public static final int TYPE_UNICAST = 1;
79 /** Indicates a MAC address is a multicast address. */
80 public static final int TYPE_MULTICAST = 2;
81 /** Indicates a MAC address is the broadcast address. */
82 public static final int TYPE_BROADCAST = 3;
83
84 private static final long VALID_LONG_MASK = (1L << 48) - 1;
85 private static final long LOCALLY_ASSIGNED_MASK = MacAddress.fromString("2:0:0:0:0:0").mAddr;
86 private static final long MULTICAST_MASK = MacAddress.fromString("1:0:0:0:0:0").mAddr;
87 private static final long OUI_MASK = MacAddress.fromString("ff:ff:ff:0:0:0").mAddr;
88 private static final long NIC_MASK = MacAddress.fromString("0:0:0:ff:ff:ff").mAddr;
89 private static final MacAddress BASE_GOOGLE_MAC = MacAddress.fromString("da:a1:19:0:0:0");
90 /** Default wifi MAC address used for a special purpose **/
91 private static final MacAddress DEFAULT_MAC_ADDRESS =
92 MacAddress.fromString(WifiInfo.DEFAULT_MAC_ADDRESS);
93
94 // Internal representation of the MAC address as a single 8 byte long.
95 // The encoding scheme sets the two most significant bytes to 0. The 6 bytes of the
96 // MAC address are encoded in the 6 least significant bytes of the long, where the first
97 // byte of the array is mapped to the 3rd highest logical byte of the long, the second
98 // byte of the array is mapped to the 4th highest logical byte of the long, and so on.
99 private final long mAddr;
100
101 private MacAddress(long addr) {
102 mAddr = (VALID_LONG_MASK & addr);
103 }
104
105 /**
106 * Returns the type of this address.
107 *
108 * @return the int constant representing the MAC address type of this MacAddress.
109 */
110 public @MacAddressType int getAddressType() {
111 if (equals(BROADCAST_ADDRESS)) {
112 return TYPE_BROADCAST;
113 }
114 if ((mAddr & MULTICAST_MASK) != 0) {
115 return TYPE_MULTICAST;
116 }
117 return TYPE_UNICAST;
118 }
119
120 /**
121 * @return true if this MacAddress is a locally assigned address.
122 */
123 public boolean isLocallyAssigned() {
124 return (mAddr & LOCALLY_ASSIGNED_MASK) != 0;
125 }
126
127 /**
128 * Convert this MacAddress to a byte array.
129 *
130 * The returned array is in network order. For example, if this MacAddress is 1:2:3:4:5:6,
131 * the returned array is [1, 2, 3, 4, 5, 6].
132 *
133 * @return a byte array representation of this MacAddress.
134 */
135 public @NonNull byte[] toByteArray() {
136 return byteAddrFromLongAddr(mAddr);
137 }
138
139 /**
140 * Returns a human-readable representation of this MacAddress.
141 * The exact format is implementation-dependent and should not be assumed to have any
142 * particular format.
143 */
144 @Override
145 public @NonNull String toString() {
146 return stringAddrFromLongAddr(mAddr);
147 }
148
149 /**
150 * @return a String representation of the OUI part of this MacAddress made of 3 hexadecimal
151 * numbers in [0,ff] joined by ':' characters.
152 */
153 public @NonNull String toOuiString() {
154 return String.format(
155 "%02x:%02x:%02x", (mAddr >> 40) & 0xff, (mAddr >> 32) & 0xff, (mAddr >> 24) & 0xff);
156 }
157
158 @Override
159 public int hashCode() {
160 return (int) ((mAddr >> 32) ^ mAddr);
161 }
162
163 @Override
Roman Kalukiewicz0b6f2902020-10-14 15:59:06 -0700164 public boolean equals(@Nullable Object o) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900165 return (o instanceof MacAddress) && ((MacAddress) o).mAddr == mAddr;
166 }
167
168 @Override
169 public void writeToParcel(Parcel out, int flags) {
170 out.writeLong(mAddr);
171 }
172
173 @Override
174 public int describeContents() {
175 return 0;
176 }
177
178 public static final @android.annotation.NonNull Parcelable.Creator<MacAddress> CREATOR =
179 new Parcelable.Creator<MacAddress>() {
180 public MacAddress createFromParcel(Parcel in) {
181 return new MacAddress(in.readLong());
182 }
183
184 public MacAddress[] newArray(int size) {
185 return new MacAddress[size];
186 }
187 };
188
189 /**
190 * Returns true if the given byte array is an valid MAC address.
191 * A valid byte array representation for a MacAddress is a non-null array of length 6.
192 *
193 * @param addr a byte array.
194 * @return true if the given byte array is not null and has the length of a MAC address.
195 *
196 * @hide
197 */
198 public static boolean isMacAddress(byte[] addr) {
199 return MacAddressUtils.isMacAddress(addr);
200 }
201
202 /**
203 * Returns the MAC address type of the MAC address represented by the given byte array,
204 * or null if the given byte array does not represent a MAC address.
205 * A valid byte array representation for a MacAddress is a non-null array of length 6.
206 *
207 * @param addr a byte array representing a MAC address.
208 * @return the int constant representing the MAC address type of the MAC address represented
209 * by the given byte array, or type UNKNOWN if the byte array is not a valid MAC address.
210 *
211 * @hide
212 */
213 public static int macAddressType(byte[] addr) {
214 if (!isMacAddress(addr)) {
215 return TYPE_UNKNOWN;
216 }
217 return MacAddress.fromBytes(addr).getAddressType();
218 }
219
220 /**
221 * Converts a String representation of a MAC address to a byte array representation.
222 * A valid String representation for a MacAddress is a series of 6 values in the
223 * range [0,ff] printed in hexadecimal and joined by ':' characters.
224 *
225 * @param addr a String representation of a MAC address.
226 * @return the byte representation of the MAC address.
227 * @throws IllegalArgumentException if the given String is not a valid representation.
228 *
229 * @hide
230 */
231 public static @NonNull byte[] byteAddrFromStringAddr(String addr) {
Remi NGUYEN VAN28028e52021-03-15 07:31:54 +0000232 Objects.requireNonNull(addr);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900233 String[] parts = addr.split(":");
234 if (parts.length != ETHER_ADDR_LEN) {
235 throw new IllegalArgumentException(addr + " was not a valid MAC address");
236 }
237 byte[] bytes = new byte[ETHER_ADDR_LEN];
238 for (int i = 0; i < ETHER_ADDR_LEN; i++) {
239 int x = Integer.valueOf(parts[i], 16);
240 if (x < 0 || 0xff < x) {
241 throw new IllegalArgumentException(addr + "was not a valid MAC address");
242 }
243 bytes[i] = (byte) x;
244 }
245 return bytes;
246 }
247
248 /**
249 * Converts a byte array representation of a MAC address to a String representation made
250 * of 6 hexadecimal numbers in [0,ff] joined by ':' characters.
251 * A valid byte array representation for a MacAddress is a non-null array of length 6.
252 *
253 * @param addr a byte array representation of a MAC address.
254 * @return the String representation of the MAC address.
255 * @throws IllegalArgumentException if the given byte array is not a valid representation.
256 *
257 * @hide
258 */
259 public static @NonNull String stringAddrFromByteAddr(byte[] addr) {
260 if (!isMacAddress(addr)) {
261 return null;
262 }
263 return String.format("%02x:%02x:%02x:%02x:%02x:%02x",
264 addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]);
265 }
266
267 private static byte[] byteAddrFromLongAddr(long addr) {
268 return MacAddressUtils.byteAddrFromLongAddr(addr);
269 }
270
271 private static long longAddrFromByteAddr(byte[] addr) {
272 return MacAddressUtils.longAddrFromByteAddr(addr);
273 }
274
275 // Internal conversion function equivalent to longAddrFromByteAddr(byteAddrFromStringAddr(addr))
276 // that avoids the allocation of an intermediary byte[].
277 private static long longAddrFromStringAddr(String addr) {
Remi NGUYEN VAN28028e52021-03-15 07:31:54 +0000278 Objects.requireNonNull(addr);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900279 String[] parts = addr.split(":");
280 if (parts.length != ETHER_ADDR_LEN) {
281 throw new IllegalArgumentException(addr + " was not a valid MAC address");
282 }
283 long longAddr = 0;
284 for (int i = 0; i < parts.length; i++) {
285 int x = Integer.valueOf(parts[i], 16);
286 if (x < 0 || 0xff < x) {
287 throw new IllegalArgumentException(addr + "was not a valid MAC address");
288 }
289 longAddr = x + (longAddr << 8);
290 }
291 return longAddr;
292 }
293
294 // Internal conversion function equivalent to stringAddrFromByteAddr(byteAddrFromLongAddr(addr))
295 // that avoids the allocation of an intermediary byte[].
296 private static @NonNull String stringAddrFromLongAddr(long addr) {
297 return String.format("%02x:%02x:%02x:%02x:%02x:%02x",
298 (addr >> 40) & 0xff,
299 (addr >> 32) & 0xff,
300 (addr >> 24) & 0xff,
301 (addr >> 16) & 0xff,
302 (addr >> 8) & 0xff,
303 addr & 0xff);
304 }
305
306 /**
307 * Creates a MacAddress from the given String representation. A valid String representation
308 * for a MacAddress is a series of 6 values in the range [0,ff] printed in hexadecimal
309 * and joined by ':' characters.
310 *
311 * @param addr a String representation of a MAC address.
312 * @return the MacAddress corresponding to the given String representation.
313 * @throws IllegalArgumentException if the given String is not a valid representation.
314 */
315 public static @NonNull MacAddress fromString(@NonNull String addr) {
316 return new MacAddress(longAddrFromStringAddr(addr));
317 }
318
319 /**
320 * Creates a MacAddress from the given byte array representation.
321 * A valid byte array representation for a MacAddress is a non-null array of length 6.
322 *
323 * @param addr a byte array representation of a MAC address.
324 * @return the MacAddress corresponding to the given byte array representation.
325 * @throws IllegalArgumentException if the given byte array is not a valid representation.
326 */
327 public static @NonNull MacAddress fromBytes(@NonNull byte[] addr) {
328 return new MacAddress(longAddrFromByteAddr(addr));
329 }
330
331 /**
332 * Returns a generated MAC address whose 24 least significant bits constituting the
333 * NIC part of the address are randomly selected and has Google OUI base.
334 *
335 * The locally assigned bit is always set to 1. The multicast bit is always set to 0.
336 *
337 * @return a random locally assigned, unicast MacAddress with Google OUI.
338 *
339 * @hide
340 */
341 public static @NonNull MacAddress createRandomUnicastAddressWithGoogleBase() {
342 return MacAddressUtils.createRandomUnicastAddress(BASE_GOOGLE_MAC, new SecureRandom());
343 }
344
345 // Convenience function for working around the lack of byte literals.
346 private static byte[] addr(int... in) {
347 if (in.length != ETHER_ADDR_LEN) {
348 throw new IllegalArgumentException(Arrays.toString(in)
349 + " was not an array with length equal to " + ETHER_ADDR_LEN);
350 }
351 byte[] out = new byte[ETHER_ADDR_LEN];
352 for (int i = 0; i < ETHER_ADDR_LEN; i++) {
353 out[i] = (byte) in[i];
354 }
355 return out;
356 }
357
358 /**
359 * Checks if this MAC Address matches the provided range.
360 *
361 * @param baseAddress MacAddress representing the base address to compare with.
362 * @param mask MacAddress representing the mask to use during comparison.
363 * @return true if this MAC Address matches the given range.
364 *
365 */
366 public boolean matches(@NonNull MacAddress baseAddress, @NonNull MacAddress mask) {
Remi NGUYEN VAN28028e52021-03-15 07:31:54 +0000367 Objects.requireNonNull(baseAddress);
368 Objects.requireNonNull(mask);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900369 return (mAddr & mask.mAddr) == (baseAddress.mAddr & mask.mAddr);
370 }
371
372 /**
373 * Create a link-local Inet6Address from the MAC address. The EUI-48 MAC address is converted
374 * to an EUI-64 MAC address per RFC 4291. The resulting EUI-64 is used to construct a link-local
375 * IPv6 address per RFC 4862.
376 *
377 * @return A link-local Inet6Address constructed from the MAC address.
378 */
379 public @Nullable Inet6Address getLinkLocalIpv6FromEui48Mac() {
380 byte[] macEui48Bytes = toByteArray();
381 byte[] addr = new byte[16];
382
383 addr[0] = (byte) 0xfe;
384 addr[1] = (byte) 0x80;
385 addr[8] = (byte) (macEui48Bytes[0] ^ (byte) 0x02); // flip the link-local bit
386 addr[9] = macEui48Bytes[1];
387 addr[10] = macEui48Bytes[2];
388 addr[11] = (byte) 0xff;
389 addr[12] = (byte) 0xfe;
390 addr[13] = macEui48Bytes[3];
391 addr[14] = macEui48Bytes[4];
392 addr[15] = macEui48Bytes[5];
393
394 try {
395 return Inet6Address.getByAddress(null, addr, 0);
396 } catch (UnknownHostException e) {
397 return null;
398 }
399 }
400}