• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2020 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 
17 package com.android.net.module.util;
18 
19 import android.os.Parcel;
20 
21 import java.net.Inet6Address;
22 import java.net.InetAddress;
23 import java.net.UnknownHostException;
24 
25 /**
26  * Collection of utilities to interact with {@link InetAddress}
27  * @hide
28  */
29 public class InetAddressUtils {
30 
31     private static final int INET6_ADDR_LENGTH = 16;
32 
33     /**
34      * Writes an InetAddress to a parcel. The address may be null. This is likely faster than
35      * calling writeSerializable.
36      * @hide
37      */
parcelInetAddress(Parcel parcel, InetAddress address, int flags)38     public static void parcelInetAddress(Parcel parcel, InetAddress address, int flags) {
39         byte[] addressArray = (address != null) ? address.getAddress() : null;
40         parcel.writeByteArray(addressArray);
41         if (address instanceof Inet6Address) {
42             final Inet6Address v6Address = (Inet6Address) address;
43             final boolean hasScopeId = v6Address.getScopeId() != 0;
44             parcel.writeBoolean(hasScopeId);
45             if (hasScopeId) parcel.writeInt(v6Address.getScopeId());
46         }
47 
48     }
49 
50     /**
51      * Reads an InetAddress from a parcel. Returns null if the address that was written was null
52      * or if the data is invalid.
53      * @hide
54      */
unparcelInetAddress(Parcel in)55     public static InetAddress unparcelInetAddress(Parcel in) {
56         byte[] addressArray = in.createByteArray();
57         if (addressArray == null) {
58             return null;
59         }
60 
61         try {
62             if (addressArray.length == INET6_ADDR_LENGTH) {
63                 final boolean hasScopeId = in.readBoolean();
64                 final int scopeId = hasScopeId ? in.readInt() : 0;
65                 return Inet6Address.getByAddress(null /* host */, addressArray, scopeId);
66             }
67 
68             return InetAddress.getByAddress(addressArray);
69         } catch (UnknownHostException e) {
70             return null;
71         }
72     }
73 
InetAddressUtils()74     private InetAddressUtils() {}
75 }
76