1 /*
2  * Copyright 2019 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 android.net.util;
18 
19 import android.annotation.NonNull;
20 import android.annotation.Nullable;
21 import android.net.RouteInfo;
22 
23 import java.net.Inet4Address;
24 import java.net.Inet6Address;
25 import java.net.InetAddress;
26 import java.util.Collection;
27 
28 /**
29  * Collection of network common utilities.
30  * @hide
31  */
32 public final class NetUtils {
33 
34     /**
35      * Check if IP address type is consistent between two InetAddress.
36      * @return true if both are the same type. False otherwise.
37      */
addressTypeMatches(@onNull InetAddress left, @NonNull InetAddress right)38     public static boolean addressTypeMatches(@NonNull InetAddress left,
39             @NonNull InetAddress right) {
40         return (((left instanceof Inet4Address) && (right instanceof Inet4Address))
41                 || ((left instanceof Inet6Address) && (right instanceof Inet6Address)));
42     }
43 
44     /**
45      * Find the route from a Collection of routes that best matches a given address.
46      * May return null if no routes are applicable.
47      * @param routes a Collection of RouteInfos to chose from
48      * @param dest the InetAddress your trying to get to
49      * @return the RouteInfo from the Collection that best fits the given address
50      */
51     @Nullable
selectBestRoute(@ullable Collection<RouteInfo> routes, @Nullable InetAddress dest)52     public static RouteInfo selectBestRoute(@Nullable Collection<RouteInfo> routes,
53             @Nullable InetAddress dest) {
54         if ((routes == null) || (dest == null)) return null;
55 
56         RouteInfo bestRoute = null;
57         // pick a longest prefix match under same address type
58         for (RouteInfo route : routes) {
59             if (addressTypeMatches(route.getDestination().getAddress(), dest)) {
60                 if ((bestRoute != null)
61                         && (bestRoute.getDestination().getPrefixLength()
62                         >= route.getDestination().getPrefixLength())) {
63                     continue;
64                 }
65                 if (route.matches(dest)) bestRoute = route;
66             }
67         }
68         return bestRoute;
69     }
70 }
71