summaryrefslogtreecommitdiff
path: root/core/java/android/net/LinkProperties.java
blob: 0706e755d133385cb3357a1d5cf97129d568bfa1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
/*
 * Copyright (C) 2010 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package android.net;

import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.SystemApi;
import android.annotation.TestApi;
import android.annotation.UnsupportedAppUsage;
import android.os.Build;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.TextUtils;

import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Hashtable;
import java.util.List;
import java.util.Objects;
import java.util.StringJoiner;

/**
 * Describes the properties of a network link.
 *
 * A link represents a connection to a network.
 * It may have multiple addresses and multiple gateways,
 * multiple dns servers but only one http proxy and one
 * network interface.
 *
 * Note that this is just a holder of data.  Modifying it
 * does not affect live networks.
 *
 */
public final class LinkProperties implements Parcelable {
    // The interface described by the network link.
    @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
    private String mIfaceName;
    private final ArrayList<LinkAddress> mLinkAddresses = new ArrayList<>();
    private final ArrayList<InetAddress> mDnses = new ArrayList<>();
    // PCSCF addresses are addresses of SIP proxies that only exist for the IMS core service.
    private final ArrayList<InetAddress> mPcscfs = new ArrayList<InetAddress>();
    private final ArrayList<InetAddress> mValidatedPrivateDnses = new ArrayList<>();
    private boolean mUsePrivateDns;
    private String mPrivateDnsServerName;
    private String mDomains;
    private ArrayList<RouteInfo> mRoutes = new ArrayList<>();
    private ProxyInfo mHttpProxy;
    private int mMtu;
    // in the format "rmem_min,rmem_def,rmem_max,wmem_min,wmem_def,wmem_max"
    private String mTcpBufferSizes;
    private IpPrefix mNat64Prefix;
    private boolean mWakeOnLanSupported;

    private static final int MIN_MTU    = 68;
    private static final int MIN_MTU_V6 = 1280;
    private static final int MAX_MTU    = 10000;

    // Stores the properties of links that are "stacked" above this link.
    // Indexed by interface name to allow modification and to prevent duplicates being added.
    private Hashtable<String, LinkProperties> mStackedLinks = new Hashtable<>();

    /**
     * @hide
     */
    public static class CompareResult<T> {
        public final List<T> removed = new ArrayList<>();
        public final List<T> added = new ArrayList<>();

        public CompareResult() {}

        public CompareResult(Collection<T> oldItems, Collection<T> newItems) {
            if (oldItems != null) {
                removed.addAll(oldItems);
            }
            if (newItems != null) {
                for (T newItem : newItems) {
                    if (!removed.remove(newItem)) {
                        added.add(newItem);
                    }
                }
            }
        }

        @Override
        public String toString() {
            return "removed=[" + TextUtils.join(",", removed)
                    + "] added=[" + TextUtils.join(",", added)
                    + "]";
        }
    }

    /**
     * @hide
     */
    @UnsupportedAppUsage(implicitMember =
            "values()[Landroid/net/LinkProperties$ProvisioningChange;")
    public enum ProvisioningChange {
        @UnsupportedAppUsage
        STILL_NOT_PROVISIONED,
        @UnsupportedAppUsage
        LOST_PROVISIONING,
        @UnsupportedAppUsage
        GAINED_PROVISIONING,
        @UnsupportedAppUsage
        STILL_PROVISIONED,
    }

    /**
     * Compare the provisioning states of two LinkProperties instances.
     *
     * @hide
     */
    @UnsupportedAppUsage
    public static ProvisioningChange compareProvisioning(
            LinkProperties before, LinkProperties after) {
        if (before.isProvisioned() && after.isProvisioned()) {
            // On dual-stack networks, DHCPv4 renewals can occasionally fail.
            // When this happens, IPv6-reachable services continue to function
            // normally but IPv4-only services (naturally) fail.
            //
            // When an application using an IPv4-only service reports a bad
            // network condition to the framework, attempts to re-validate
            // the network succeed (since we support IPv6-only networks) and
            // nothing is changed.
            //
            // For users, this is confusing and unexpected behaviour, and is
            // not necessarily easy to diagnose.  Therefore, we treat changing
            // from a dual-stack network to an IPv6-only network equivalent to
            // a total loss of provisioning.
            //
            // For one such example of this, see b/18867306.
            //
            // Additionally, losing IPv6 provisioning can result in TCP
            // connections getting stuck until timeouts fire and other
            // baffling failures. Therefore, loss of either IPv4 or IPv6 on a
            // previously dual-stack network is deemed a lost of provisioning.
            if ((before.isIpv4Provisioned() && !after.isIpv4Provisioned())
                    || (before.isIpv6Provisioned() && !after.isIpv6Provisioned())) {
                return ProvisioningChange.LOST_PROVISIONING;
            }
            return ProvisioningChange.STILL_PROVISIONED;
        } else if (before.isProvisioned() && !after.isProvisioned()) {
            return ProvisioningChange.LOST_PROVISIONING;
        } else if (!before.isProvisioned() && after.isProvisioned()) {
            return ProvisioningChange.GAINED_PROVISIONING;
        } else {  // !before.isProvisioned() && !after.isProvisioned()
            return ProvisioningChange.STILL_NOT_PROVISIONED;
        }
    }

    /**
     * Constructs a new {@code LinkProperties} with default values.
     */
    public LinkProperties() {
    }

    /**
     * @hide
     */
    @SystemApi
    @TestApi
    public LinkProperties(@Nullable LinkProperties source) {
        if (source != null) {
            mIfaceName = source.mIfaceName;
            mLinkAddresses.addAll(source.mLinkAddresses);
            mDnses.addAll(source.mDnses);
            mValidatedPrivateDnses.addAll(source.mValidatedPrivateDnses);
            mUsePrivateDns = source.mUsePrivateDns;
            mPrivateDnsServerName = source.mPrivateDnsServerName;
            mPcscfs.addAll(source.mPcscfs);
            mDomains = source.mDomains;
            mRoutes.addAll(source.mRoutes);
            mHttpProxy = (source.mHttpProxy == null) ? null : new ProxyInfo(source.mHttpProxy);
            for (LinkProperties l: source.mStackedLinks.values()) {
                addStackedLink(l);
            }
            setMtu(source.mMtu);
            mTcpBufferSizes = source.mTcpBufferSizes;
            mNat64Prefix = source.mNat64Prefix;
            mWakeOnLanSupported = source.mWakeOnLanSupported;
        }
    }

    /**
     * Sets the interface name for this link.  All {@link RouteInfo} already set for this
     * will have their interface changed to match this new value.
     *
     * @param iface The name of the network interface used for this link.
     */
    public void setInterfaceName(@Nullable String iface) {
        mIfaceName = iface;
        ArrayList<RouteInfo> newRoutes = new ArrayList<>(mRoutes.size());
        for (RouteInfo route : mRoutes) {
            newRoutes.add(routeWithInterface(route));
        }
        mRoutes = newRoutes;
    }

    /**
     * Gets the interface name for this link.  May be {@code null} if not set.
     *
     * @return The interface name set for this link or {@code null}.
     */
    public @Nullable String getInterfaceName() {
        return mIfaceName;
    }

    /**
     * @hide
     */
    @UnsupportedAppUsage
    public @NonNull List<String> getAllInterfaceNames() {
        List<String> interfaceNames = new ArrayList<>(mStackedLinks.size() + 1);
        if (mIfaceName != null) interfaceNames.add(mIfaceName);
        for (LinkProperties stacked: mStackedLinks.values()) {
            interfaceNames.addAll(stacked.getAllInterfaceNames());
        }
        return interfaceNames;
    }

    /**
     * Returns all the addresses on this link.  We often think of a link having a single address,
     * however, particularly with Ipv6 several addresses are typical.  Note that the
     * {@code LinkProperties} actually contains {@link LinkAddress} objects which also include
     * prefix lengths for each address.  This is a simplified utility alternative to
     * {@link LinkProperties#getLinkAddresses}.
     *
     * @return An unmodifiable {@link List} of {@link InetAddress} for this link.
     * @hide
     */
    @UnsupportedAppUsage
    public @NonNull List<InetAddress> getAddresses() {
        final List<InetAddress> addresses = new ArrayList<>();
        for (LinkAddress linkAddress : mLinkAddresses) {
            addresses.add(linkAddress.getAddress());
        }
        return Collections.unmodifiableList(addresses);
    }

    /**
     * Returns all the addresses on this link and all the links stacked above it.
     * @hide
     */
    @UnsupportedAppUsage
    public @NonNull List<InetAddress> getAllAddresses() {
        List<InetAddress> addresses = new ArrayList<>();
        for (LinkAddress linkAddress : mLinkAddresses) {
            addresses.add(linkAddress.getAddress());
        }
        for (LinkProperties stacked: mStackedLinks.values()) {
            addresses.addAll(stacked.getAllAddresses());
        }
        return addresses;
    }

    private int findLinkAddressIndex(LinkAddress address) {
        for (int i = 0; i < mLinkAddresses.size(); i++) {
            if (mLinkAddresses.get(i).isSameAddressAs(address)) {
                return i;
            }
        }
        return -1;
    }

    /**
     * Adds a {@link LinkAddress} to this {@code LinkProperties} if a {@link LinkAddress} of the
     * same address/prefix does not already exist.  If it does exist it is replaced.
     * @param address The {@code LinkAddress} to add.
     * @return true if {@code address} was added or updated, false otherwise.
     * @hide
     */
    @SystemApi
    @TestApi
    public boolean addLinkAddress(@NonNull LinkAddress address) {
        if (address == null) {
            return false;
        }
        int i = findLinkAddressIndex(address);
        if (i < 0) {
            // Address was not present. Add it.
            mLinkAddresses.add(address);
            return true;
        } else if (mLinkAddresses.get(i).equals(address)) {
            // Address was present and has same properties. Do nothing.
            return false;
        } else {
            // Address was present and has different properties. Update it.
            mLinkAddresses.set(i, address);
            return true;
        }
    }

    /**
     * Removes a {@link LinkAddress} from this {@code LinkProperties}.  Specifically, matches
     * and {@link LinkAddress} with the same address and prefix.
     *
     * @param toRemove A {@link LinkAddress} specifying the address to remove.
     * @return true if the address was removed, false if it did not exist.
     * @hide
     */
    @SystemApi
    @TestApi
    public boolean removeLinkAddress(@NonNull LinkAddress toRemove) {
        int i = findLinkAddressIndex(toRemove);
        if (i >= 0) {
            mLinkAddresses.remove(i);
            return true;
        }
        return false;
    }

    /**
     * Returns all the {@link LinkAddress} on this link.  Typically a link will have
     * one IPv4 address and one or more IPv6 addresses.
     *
     * @return An unmodifiable {@link List} of {@link LinkAddress} for this link.
     */
    public @NonNull List<LinkAddress> getLinkAddresses() {
        return Collections.unmodifiableList(mLinkAddresses);
    }

    /**
     * Returns all the addresses on this link and all the links stacked above it.
     * @hide
     */
    @UnsupportedAppUsage
    public List<LinkAddress> getAllLinkAddresses() {
        List<LinkAddress> addresses = new ArrayList<>(mLinkAddresses);
        for (LinkProperties stacked: mStackedLinks.values()) {
            addresses.addAll(stacked.getAllLinkAddresses());
        }
        return addresses;
    }

    /**
     * Replaces the {@link LinkAddress} in this {@code LinkProperties} with
     * the given {@link Collection} of {@link LinkAddress}.
     *
     * @param addresses The {@link Collection} of {@link LinkAddress} to set in this
     *                  object.
     */
    public void setLinkAddresses(@NonNull Collection<LinkAddress> addresses) {
        mLinkAddresses.clear();
        for (LinkAddress address: addresses) {
            addLinkAddress(address);
        }
    }

    /**
     * Adds the given {@link InetAddress} to the list of DNS servers, if not present.
     *
     * @param dnsServer The {@link InetAddress} to add to the list of DNS servers.
     * @return true if the DNS server was added, false if it was already present.
     * @hide
     */
    @TestApi
    @SystemApi
    public boolean addDnsServer(@NonNull InetAddress dnsServer) {
        if (dnsServer != null && !mDnses.contains(dnsServer)) {
            mDnses.add(dnsServer);
            return true;
        }
        return false;
    }

    /**
     * Removes the given {@link InetAddress} from the list of DNS servers.
     *
     * @param dnsServer The {@link InetAddress} to remove from the list of DNS servers.
     * @return true if the DNS server was removed, false if it did not exist.
     * @hide
     */
    @TestApi
    @SystemApi
    public boolean removeDnsServer(@NonNull InetAddress dnsServer) {
        return mDnses.remove(dnsServer);
    }

    /**
     * Replaces the DNS servers in this {@code LinkProperties} with
     * the given {@link Collection} of {@link InetAddress} objects.
     *
     * @param dnsServers The {@link Collection} of DNS servers to set in this object.
     */
    public void setDnsServers(@NonNull Collection<InetAddress> dnsServers) {
        mDnses.clear();
        for (InetAddress dnsServer: dnsServers) {
            addDnsServer(dnsServer);
        }
    }

    /**
     * Returns all the {@link InetAddress} for DNS servers on this link.
     *
     * @return An unmodifiable {@link List} of {@link InetAddress} for DNS servers on
     *         this link.
     */
    public @NonNull List<InetAddress> getDnsServers() {
        return Collections.unmodifiableList(mDnses);
    }

    /**
     * Set whether private DNS is currently in use on this network.
     *
     * @param usePrivateDns The private DNS state.
     * @hide
     */
    @TestApi
    @SystemApi
    public void setUsePrivateDns(boolean usePrivateDns) {
        mUsePrivateDns = usePrivateDns;
    }

    /**
     * Returns whether private DNS is currently in use on this network. When
     * private DNS is in use, applications must not send unencrypted DNS
     * queries as doing so could reveal private user information. Furthermore,
     * if private DNS is in use and {@link #getPrivateDnsServerName} is not
     * {@code null}, DNS queries must be sent to the specified DNS server.
     *
     * @return {@code true} if private DNS is in use, {@code false} otherwise.
     */
    public boolean isPrivateDnsActive() {
        return mUsePrivateDns;
    }

    /**
     * Set the name of the private DNS server to which private DNS queries
     * should be sent when in strict mode. This value should be {@code null}
     * when private DNS is off or in opportunistic mode.
     *
     * @param privateDnsServerName The private DNS server name.
     * @hide
     */
    @TestApi
    @SystemApi
    public void setPrivateDnsServerName(@Nullable String privateDnsServerName) {
        mPrivateDnsServerName = privateDnsServerName;
    }

    /**
     * Returns the private DNS server name that is in use. If not {@code null},
     * private DNS is in strict mode. In this mode, applications should ensure
     * that all DNS queries are encrypted and sent to this hostname and that
     * queries are only sent if the hostname's certificate is valid. If
     * {@code null} and {@link #isPrivateDnsActive} is {@code true}, private
     * DNS is in opportunistic mode, and applications should ensure that DNS
     * queries are encrypted and sent to a DNS server returned by
     * {@link #getDnsServers}. System DNS will handle each of these cases
     * correctly, but applications implementing their own DNS lookups must make
     * sure to follow these requirements.
     *
     * @return The private DNS server name.
     */
    public @Nullable String getPrivateDnsServerName() {
        return mPrivateDnsServerName;
    }

    /**
     * Adds the given {@link InetAddress} to the list of validated private DNS servers,
     * if not present. This is distinct from the server name in that these are actually
     * resolved addresses.
     *
     * @param dnsServer The {@link InetAddress} to add to the list of validated private DNS servers.
     * @return true if the DNS server was added, false if it was already present.
     * @hide
     */
    public boolean addValidatedPrivateDnsServer(@NonNull InetAddress dnsServer) {
        if (dnsServer != null && !mValidatedPrivateDnses.contains(dnsServer)) {
            mValidatedPrivateDnses.add(dnsServer);
            return true;
        }
        return false;
    }

    /**
     * Removes the given {@link InetAddress} from the list of validated private DNS servers.
     *
     * @param dnsServer The {@link InetAddress} to remove from the list of validated private DNS
     *        servers.
     * @return true if the DNS server was removed, false if it did not exist.
     * @hide
     */
    public boolean removeValidatedPrivateDnsServer(@NonNull InetAddress dnsServer) {
        return mValidatedPrivateDnses.remove(dnsServer);
    }

    /**
     * Replaces the validated private DNS servers in this {@code LinkProperties} with
     * the given {@link Collection} of {@link InetAddress} objects.
     *
     * @param dnsServers The {@link Collection} of validated private DNS servers to set in this
     *        object.
     * @hide
     */
    @TestApi
    @SystemApi
    public void setValidatedPrivateDnsServers(@NonNull Collection<InetAddress> dnsServers) {
        mValidatedPrivateDnses.clear();
        for (InetAddress dnsServer: dnsServers) {
            addValidatedPrivateDnsServer(dnsServer);
        }
    }

    /**
     * Returns all the {@link InetAddress} for validated private DNS servers on this link.
     * These are resolved from the private DNS server name.
     *
     * @return An unmodifiable {@link List} of {@link InetAddress} for validated private
     *         DNS servers on this link.
     * @hide
     */
    @TestApi
    @SystemApi
    public @NonNull List<InetAddress> getValidatedPrivateDnsServers() {
        return Collections.unmodifiableList(mValidatedPrivateDnses);
    }

    /**
     * Adds the given {@link InetAddress} to the list of PCSCF servers, if not present.
     *
     * @param pcscfServer The {@link InetAddress} to add to the list of PCSCF servers.
     * @return true if the PCSCF server was added, false otherwise.
     * @hide
     */
    public boolean addPcscfServer(@NonNull InetAddress pcscfServer) {
        if (pcscfServer != null && !mPcscfs.contains(pcscfServer)) {
            mPcscfs.add(pcscfServer);
            return true;
        }
        return false;
    }

    /**
     * Removes the given {@link InetAddress} from the list of PCSCF servers.
     *
     * @param pcscfServer The {@link InetAddress} to remove from the list of PCSCF servers.
     * @return true if the PCSCF server was removed, false otherwise.
     * @hide
     */
    public boolean removePcscfServer(@NonNull InetAddress pcscfServer) {
        return mPcscfs.remove(pcscfServer);
    }

    /**
     * Replaces the PCSCF servers in this {@code LinkProperties} with
     * the given {@link Collection} of {@link InetAddress} objects.
     *
     * @param pcscfServers The {@link Collection} of PCSCF servers to set in this object.
     * @hide
     */
    @SystemApi
    @TestApi
    public void setPcscfServers(@NonNull Collection<InetAddress> pcscfServers) {
        mPcscfs.clear();
        for (InetAddress pcscfServer: pcscfServers) {
            addPcscfServer(pcscfServer);
        }
    }

    /**
     * Returns all the {@link InetAddress} for PCSCF servers on this link.
     *
     * @return An unmodifiable {@link List} of {@link InetAddress} for PCSCF servers on
     *         this link.
     * @hide
     */
    @SystemApi
    @TestApi
    public @NonNull List<InetAddress> getPcscfServers() {
        return Collections.unmodifiableList(mPcscfs);
    }

    /**
     * Sets the DNS domain search path used on this link.
     *
     * @param domains A {@link String} listing in priority order the comma separated
     *                domains to search when resolving host names on this link.
     */
    public void setDomains(@Nullable String domains) {
        mDomains = domains;
    }

    /**
     * Get the DNS domains search path set for this link. May be {@code null} if not set.
     *
     * @return A {@link String} containing the comma separated domains to search when resolving host
     *         names on this link or {@code null}.
     */
    public @Nullable String getDomains() {
        return mDomains;
    }

    /**
     * Sets the Maximum Transmission Unit size to use on this link.  This should not be used
     * unless the system default (1500) is incorrect.  Values less than 68 or greater than
     * 10000 will be ignored.
     *
     * @param mtu The MTU to use for this link.
     */
    public void setMtu(int mtu) {
        mMtu = mtu;
    }

    /**
     * Gets any non-default MTU size set for this link.  Note that if the default is being used
     * this will return 0.
     *
     * @return The mtu value set for this link.
     */
    public int getMtu() {
        return mMtu;
    }

    /**
     * Sets the tcp buffers sizes to be used when this link is the system default.
     * Should be of the form "rmem_min,rmem_def,rmem_max,wmem_min,wmem_def,wmem_max".
     *
     * @param tcpBufferSizes The tcp buffers sizes to use.
     *
     * @hide
     */
    @TestApi
    @SystemApi
    public void setTcpBufferSizes(@Nullable String tcpBufferSizes) {
        mTcpBufferSizes = tcpBufferSizes;
    }

    /**
     * Gets the tcp buffer sizes. May be {@code null} if not set.
     *
     * @return the tcp buffer sizes to use when this link is the system default or {@code null}.
     *
     * @hide
     */
    @TestApi
    @SystemApi
    public @Nullable String getTcpBufferSizes() {
        return mTcpBufferSizes;
    }

    private RouteInfo routeWithInterface(RouteInfo route) {
        return new RouteInfo(
            route.getDestination(),
            route.getGateway(),
            mIfaceName,
            route.getType());
    }

    /**
     * Adds a {@link RouteInfo} to this {@code LinkProperties}, if not present. If the
     * {@link RouteInfo} had an interface name set and that differs from the interface set for this
     * {@code LinkProperties} an {@link IllegalArgumentException} will be thrown.  The proper
     * course is to add either un-named or properly named {@link RouteInfo}.
     *
     * @param route A {@link RouteInfo} to add to this object.
     * @return {@code false} if the route was already present, {@code true} if it was added.
     */
    public boolean addRoute(@NonNull RouteInfo route) {
        String routeIface = route.getInterface();
        if (routeIface != null && !routeIface.equals(mIfaceName)) {
            throw new IllegalArgumentException(
                    "Route added with non-matching interface: " + routeIface
                            + " vs. " + mIfaceName);
        }
        route = routeWithInterface(route);
        if (!mRoutes.contains(route)) {
            mRoutes.add(route);
            return true;
        }
        return false;
    }

    /**
     * Removes a {@link RouteInfo} from this {@code LinkProperties}, if present. The route must
     * specify an interface and the interface must match the interface of this
     * {@code LinkProperties}, or it will not be removed.
     *
     * @return {@code true} if the route was removed, {@code false} if it was not present.
     *
     * @hide
     */
    @TestApi
    @SystemApi
    public boolean removeRoute(@NonNull RouteInfo route) {
        return Objects.equals(mIfaceName, route.getInterface()) && mRoutes.remove(route);
    }

    /**
     * Returns all the {@link RouteInfo} set on this link.
     *
     * @return An unmodifiable {@link List} of {@link RouteInfo} for this link.
     */
    public @NonNull List<RouteInfo> getRoutes() {
        return Collections.unmodifiableList(mRoutes);
    }

    /**
     * Make sure this LinkProperties instance contains routes that cover the local subnet
     * of its link addresses. Add any route that is missing.
     * @hide
     */
    public void ensureDirectlyConnectedRoutes() {
        for (LinkAddress addr : mLinkAddresses) {
            addRoute(new RouteInfo(addr, null, mIfaceName));
        }
    }

    /**
     * Returns all the routes on this link and all the links stacked above it.
     * @hide
     */
    @UnsupportedAppUsage
    public @NonNull List<RouteInfo> getAllRoutes() {
        List<RouteInfo> routes = new ArrayList<>(mRoutes);
        for (LinkProperties stacked: mStackedLinks.values()) {
            routes.addAll(stacked.getAllRoutes());
        }
        return routes;
    }

    /**
     * Sets the recommended {@link ProxyInfo} to use on this link, or {@code null} for none.
     * Note that Http Proxies are only a hint - the system recommends their use, but it does
     * not enforce it and applications may ignore them.
     *
     * @param proxy A {@link ProxyInfo} defining the HTTP Proxy to use on this link.
     */
    public void setHttpProxy(@Nullable ProxyInfo proxy) {
        mHttpProxy = proxy;
    }

    /**
     * Gets the recommended {@link ProxyInfo} (or {@code null}) set on this link.
     *
     * @return The {@link ProxyInfo} set on this link or {@code null}.
     */
    public @Nullable ProxyInfo getHttpProxy() {
        return mHttpProxy;
    }

    /**
     * Returns the NAT64 prefix in use on this link, if any.
     *
     * @return the NAT64 prefix or {@code null}.
     * @hide
     */
    @SystemApi
    @TestApi
    public @Nullable IpPrefix getNat64Prefix() {
        return mNat64Prefix;
    }

    /**
     * Sets the NAT64 prefix in use on this link.
     *
     * Currently, only 96-bit prefixes (i.e., where the 32-bit IPv4 address is at the end of the
     * 128-bit IPv6 address) are supported or {@code null} for no prefix.
     *
     * @param prefix the NAT64 prefix.
     * @hide
     */
    @SystemApi
    @TestApi
    public void setNat64Prefix(@Nullable IpPrefix prefix) {
        if (prefix != null && prefix.getPrefixLength() != 96) {
            throw new IllegalArgumentException("Only 96-bit prefixes are supported: " + prefix);
        }
        mNat64Prefix = prefix;  // IpPrefix objects are immutable.
    }

    /**
     * Adds a stacked link.
     *
     * If there is already a stacked link with the same interface name as link,
     * that link is replaced with link. Otherwise, link is added to the list
     * of stacked links.
     *
     * @param link The link to add.
     * @return true if the link was stacked, false otherwise.
     * @hide
     */
    @UnsupportedAppUsage
    public boolean addStackedLink(@NonNull LinkProperties link) {
        if (link.getInterfaceName() != null) {
            mStackedLinks.put(link.getInterfaceName(), link);
            return true;
        }
        return false;
    }

    /**
     * Removes a stacked link.
     *
     * If there is a stacked link with the given interface name, it is
     * removed. Otherwise, nothing changes.
     *
     * @param iface The interface name of the link to remove.
     * @return true if the link was removed, false otherwise.
     * @hide
     */
    public boolean removeStackedLink(@NonNull String iface) {
        LinkProperties removed = mStackedLinks.remove(iface);
        return removed != null;
    }

    /**
     * Returns all the links stacked on top of this link.
     * @hide
     */
    @UnsupportedAppUsage
    public @NonNull List<LinkProperties> getStackedLinks() {
        if (mStackedLinks.isEmpty()) {
            return Collections.emptyList();
        }
        final List<LinkProperties> stacked = new ArrayList<>();
        for (LinkProperties link : mStackedLinks.values()) {
            stacked.add(new LinkProperties(link));
        }
        return Collections.unmodifiableList(stacked);
    }

    /**
     * Clears this object to its initial state.
     */
    public void clear() {
        mIfaceName = null;
        mLinkAddresses.clear();
        mDnses.clear();
        mUsePrivateDns = false;
        mPrivateDnsServerName = null;
        mPcscfs.clear();
        mDomains = null;
        mRoutes.clear();
        mHttpProxy = null;
        mStackedLinks.clear();
        mMtu = 0;
        mTcpBufferSizes = null;
        mNat64Prefix = null;
        mWakeOnLanSupported = false;
    }

    /**
     * Implement the Parcelable interface
     */
    public int describeContents() {
        return 0;
    }

    @Override
    public String toString() {
        // Space as a separator, so no need for spaces at start/end of the individual fragments.
        final StringJoiner resultJoiner = new StringJoiner(" ", "{", "}");

        if (mIfaceName != null) {
            resultJoiner.add("InterfaceName:");
            resultJoiner.add(mIfaceName);
        }

        resultJoiner.add("LinkAddresses: [");
        if (!mLinkAddresses.isEmpty()) {
            resultJoiner.add(TextUtils.join(",", mLinkAddresses));
        }
        resultJoiner.add("]");

        resultJoiner.add("DnsAddresses: [");
        if (!mDnses.isEmpty()) {
            resultJoiner.add(TextUtils.join(",", mDnses));
        }
        resultJoiner.add("]");

        if (mUsePrivateDns) {
            resultJoiner.add("UsePrivateDns: true");
        }

        if (mPrivateDnsServerName != null) {
            resultJoiner.add("PrivateDnsServerName:");
            resultJoiner.add(mPrivateDnsServerName);
        }

        if (!mPcscfs.isEmpty()) {
            resultJoiner.add("PcscfAddresses: [");
            resultJoiner.add(TextUtils.join(",", mPcscfs));
            resultJoiner.add("]");
        }

        if (!mValidatedPrivateDnses.isEmpty()) {
            final StringJoiner validatedPrivateDnsesJoiner =
                    new StringJoiner(",", "ValidatedPrivateDnsAddresses: [", "]");
            for (final InetAddress addr : mValidatedPrivateDnses) {
                validatedPrivateDnsesJoiner.add(addr.getHostAddress());
            }
            resultJoiner.add(validatedPrivateDnsesJoiner.toString());
        }

        resultJoiner.add("Domains:");
        resultJoiner.add(mDomains);

        resultJoiner.add("MTU:");
        resultJoiner.add(Integer.toString(mMtu));

        if (mWakeOnLanSupported) {
            resultJoiner.add("WakeOnLanSupported: true");
        }

        if (mTcpBufferSizes != null) {
            resultJoiner.add("TcpBufferSizes:");
            resultJoiner.add(mTcpBufferSizes);
        }

        resultJoiner.add("Routes: [");
        if (!mRoutes.isEmpty()) {
            resultJoiner.add(TextUtils.join(",", mRoutes));
        }
        resultJoiner.add("]");

        if (mHttpProxy != null) {
            resultJoiner.add("HttpProxy:");
            resultJoiner.add(mHttpProxy.toString());
        }

        if (mNat64Prefix != null) {
            resultJoiner.add("Nat64Prefix:");
            resultJoiner.add(mNat64Prefix.toString());
        }

        final Collection<LinkProperties> stackedLinksValues = mStackedLinks.values();
        if (!stackedLinksValues.isEmpty()) {
            final StringJoiner stackedLinksJoiner = new StringJoiner(",", "Stacked: [", "]");
            for (final LinkProperties lp : stackedLinksValues) {
                stackedLinksJoiner.add("[ " + lp + " ]");
            }
            resultJoiner.add(stackedLinksJoiner.toString());
        }

        return resultJoiner.toString();
    }

    /**
     * Returns true if this link has an IPv4 address.
     *
     * @return {@code true} if there is an IPv4 address, {@code false} otherwise.
     * @hide
     */
    @TestApi
    @SystemApi
    public boolean hasIpv4Address() {
        for (LinkAddress address : mLinkAddresses) {
            if (address.getAddress() instanceof Inet4Address) {
                return true;
            }
        }
        return false;
    }

    /**
     * For backward compatibility.
     * This was annotated with @UnsupportedAppUsage in P, so we can't remove the method completely
     * just yet.
     * @return {@code true} if there is an IPv4 address, {@code false} otherwise.
     * @hide
     */
    @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
    public boolean hasIPv4Address() {
        return hasIpv4Address();
    }

    /**
     * Returns true if this link or any of its stacked interfaces has an IPv4 address.
     *
     * @return {@code true} if there is an IPv4 address, {@code false} otherwise.
     */
    private boolean hasIpv4AddressOnInterface(String iface) {
        // mIfaceName can be null.
        return (Objects.equals(iface, mIfaceName) && hasIpv4Address())
                || (iface != null && mStackedLinks.containsKey(iface)
                        && mStackedLinks.get(iface).hasIpv4Address());
    }

    /**
     * Returns true if this link has a global preferred IPv6 address.
     *
     * @return {@code true} if there is a global preferred IPv6 address, {@code false} otherwise.
     * @hide
     */
    @TestApi
    @SystemApi
    public boolean hasGlobalIpv6Address() {
        for (LinkAddress address : mLinkAddresses) {
          if (address.getAddress() instanceof Inet6Address && address.isGlobalPreferred()) {
            return true;
          }
        }
        return false;
    }

    /**
     * For backward compatibility.
     * This was annotated with @UnsupportedAppUsage in P, so we can't remove the method completely
     * just yet.
     * @return {@code true} if there is a global preferred IPv6 address, {@code false} otherwise.
     * @hide
     */
    @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
    public boolean hasGlobalIPv6Address() {
        return hasGlobalIpv6Address();
    }

    /**
     * Returns true if this link has an IPv4 default route.
     *
     * @return {@code true} if there is an IPv4 default route, {@code false} otherwise.
     * @hide
     */
    @UnsupportedAppUsage
    public boolean hasIpv4DefaultRoute() {
        for (RouteInfo r : mRoutes) {
            if (r.isIPv4Default()) {
                return true;
            }
        }
        return false;
    }

    /**
     * For backward compatibility.
     * This was annotated with @UnsupportedAppUsage in P, so we can't remove the method completely
     * just yet.
     * @return {@code true} if there is an IPv4 default route, {@code false} otherwise.
     * @hide
     */
    @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
    public boolean hasIPv4DefaultRoute() {
        return hasIpv4DefaultRoute();
    }

    /**
     * Returns true if this link has an IPv6 default route.
     *
     * @return {@code true} if there is an IPv6 default route, {@code false} otherwise.
     * @hide
     */
    @TestApi
    @SystemApi
    public boolean hasIpv6DefaultRoute() {
        for (RouteInfo r : mRoutes) {
            if (r.isIPv6Default()) {
                return true;
            }
        }
        return false;
    }

    /**
     * For backward compatibility.
     * This was annotated with @UnsupportedAppUsage in P, so we can't remove the method completely
     * just yet.
     * @return {@code true} if there is an IPv6 default route, {@code false} otherwise.
     * @hide
     */
    @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
    public boolean hasIPv6DefaultRoute() {
        return hasIpv6DefaultRoute();
    }

    /**
     * Returns true if this link has an IPv4 DNS server.
     *
     * @return {@code true} if there is an IPv4 DNS server, {@code false} otherwise.
     * @hide
     */
    @UnsupportedAppUsage
    public boolean hasIpv4DnsServer() {
        for (InetAddress ia : mDnses) {
            if (ia instanceof Inet4Address) {
                return true;
            }
        }
        return false;
    }

    /**
     * For backward compatibility.
     * This was annotated with @UnsupportedAppUsage in P, so we can't remove the method completely
     * just yet.
     * @return {@code true} if there is an IPv4 DNS server, {@code false} otherwise.
     * @hide
     */
    @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
    public boolean hasIPv4DnsServer() {
        return hasIpv4DnsServer();
    }

    /**
     * Returns true if this link has an IPv6 DNS server.
     *
     * @return {@code true} if there is an IPv6 DNS server, {@code false} otherwise.
     * @hide
     */
    @UnsupportedAppUsage
    public boolean hasIpv6DnsServer() {
        for (InetAddress ia : mDnses) {
            if (ia instanceof Inet6Address) {
                return true;
            }
        }
        return false;
    }

    /**
     * For backward compatibility.
     * This was annotated with @UnsupportedAppUsage in P, so we can't remove the method completely
     * just yet.
     * @return {@code true} if there is an IPv6 DNS server, {@code false} otherwise.
     * @hide
     */
    @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
    public boolean hasIPv6DnsServer() {
        return hasIpv6DnsServer();
    }

    /**
     * Returns true if this link has an IPv4 PCSCF server.
     *
     * @return {@code true} if there is an IPv4 PCSCF server, {@code false} otherwise.
     * @hide
     */
    public boolean hasIpv4PcscfServer() {
        for (InetAddress ia : mPcscfs) {
          if (ia instanceof Inet4Address) {
            return true;
          }
        }
        return false;
    }

    /**
     * Returns true if this link has an IPv6 PCSCF server.
     *
     * @return {@code true} if there is an IPv6 PCSCF server, {@code false} otherwise.
     * @hide
     */
    public boolean hasIpv6PcscfServer() {
        for (InetAddress ia : mPcscfs) {
          if (ia instanceof Inet6Address) {
            return true;
          }
        }
        return false;
    }

    /**
     * Returns true if this link is provisioned for global IPv4 connectivity.
     * This requires an IP address, default route, and DNS server.
     *
     * @return {@code true} if the link is provisioned, {@code false} otherwise.
     * @hide
     */
    @TestApi
    @SystemApi
    public boolean isIpv4Provisioned() {
        return (hasIpv4Address()
                && hasIpv4DefaultRoute()
                && hasIpv4DnsServer());
    }

    /**
     * Returns true if this link is provisioned for global IPv6 connectivity.
     * This requires an IP address, default route, and DNS server.
     *
     * @return {@code true} if the link is provisioned, {@code false} otherwise.
     * @hide
     */
    @TestApi
    @SystemApi
    public boolean isIpv6Provisioned() {
        return (hasGlobalIpv6Address()
                && hasIpv6DefaultRoute()
                && hasIpv6DnsServer());
    }

    /**
     * For backward compatibility.
     * This was annotated with @UnsupportedAppUsage in P, so we can't remove the method completely
     * just yet.
     * @return {@code true} if the link is provisioned, {@code false} otherwise.
     * @hide
     */
    @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
    public boolean isIPv6Provisioned() {
        return isIpv6Provisioned();
    }


    /**
     * Returns true if this link is provisioned for global connectivity,
     * for at least one Internet Protocol family.
     *
     * @return {@code true} if the link is provisioned, {@code false} otherwise.
     * @hide
     */
    @TestApi
    @SystemApi
    public boolean isProvisioned() {
        return (isIpv4Provisioned() || isIpv6Provisioned());
    }

    /**
     * Evaluate whether the {@link InetAddress} is considered reachable.
     *
     * @return {@code true} if the given {@link InetAddress} is considered reachable,
     *         {@code false} otherwise.
     * @hide
     */
    @TestApi
    @SystemApi
    public boolean isReachable(@NonNull InetAddress ip) {
        final List<RouteInfo> allRoutes = getAllRoutes();
        // If we don't have a route to this IP address, it's not reachable.
        final RouteInfo bestRoute = RouteInfo.selectBestRoute(allRoutes, ip);
        if (bestRoute == null) {
            return false;
        }

        // TODO: better source address evaluation for destination addresses.

        if (ip instanceof Inet4Address) {
            // For IPv4, it suffices for now to simply have any address.
            return hasIpv4AddressOnInterface(bestRoute.getInterface());
        } else if (ip instanceof Inet6Address) {
            if (ip.isLinkLocalAddress()) {
                // For now, just make sure link-local destinations have
                // scopedIds set, since transmits will generally fail otherwise.
                // TODO: verify it matches the ifindex of one of the interfaces.
                return (((Inet6Address)ip).getScopeId() != 0);
            }  else {
                // For non-link-local destinations check that either the best route
                // is directly connected or that some global preferred address exists.
                // TODO: reconsider all cases (disconnected ULA networks, ...).
                return (!bestRoute.hasGateway() || hasGlobalIpv6Address());
            }
        }

        return false;
    }

    /**
     * Compares this {@code LinkProperties} interface name against the target
     *
     * @param target LinkProperties to compare.
     * @return {@code true} if both are identical, {@code false} otherwise.
     * @hide
     */
    @UnsupportedAppUsage
    public boolean isIdenticalInterfaceName(@NonNull LinkProperties target) {
        return TextUtils.equals(getInterfaceName(), target.getInterfaceName());
    }

    /**
     * Compares this {@code LinkProperties} interface addresses against the target
     *
     * @param target LinkProperties to compare.
     * @return {@code true} if both are identical, {@code false} otherwise.
     * @hide
     */
    @UnsupportedAppUsage
    public boolean isIdenticalAddresses(@NonNull LinkProperties target) {
        Collection<InetAddress> targetAddresses = target.getAddresses();
        Collection<InetAddress> sourceAddresses = getAddresses();
        return (sourceAddresses.size() == targetAddresses.size()) ?
                    sourceAddresses.containsAll(targetAddresses) : false;
    }

    /**
     * Compares this {@code LinkProperties} DNS addresses against the target
     *
     * @param target LinkProperties to compare.
     * @return {@code true} if both are identical, {@code false} otherwise.
     * @hide
     */
    @UnsupportedAppUsage
    public boolean isIdenticalDnses(@NonNull LinkProperties target) {
        Collection<InetAddress> targetDnses = target.getDnsServers();
        String targetDomains = target.getDomains();
        if (mDomains == null) {
            if (targetDomains != null) return false;
        } else {
            if (!mDomains.equals(targetDomains)) return false;
        }
        return (mDnses.size() == targetDnses.size()) ?
                mDnses.containsAll(targetDnses) : false;
    }

    /**
     * Compares this {@code LinkProperties} private DNS settings against the
     * target.
     *
     * @param target LinkProperties to compare.
     * @return {@code true} if both are identical, {@code false} otherwise.
     * @hide
     */
    public boolean isIdenticalPrivateDns(@NonNull LinkProperties target) {
        return (isPrivateDnsActive() == target.isPrivateDnsActive()
                && TextUtils.equals(getPrivateDnsServerName(),
                target.getPrivateDnsServerName()));
    }

    /**
     * Compares this {@code LinkProperties} validated private DNS addresses against
     * the target
     *
     * @param target LinkProperties to compare.
     * @return {@code true} if both are identical, {@code false} otherwise.
     * @hide
     */
    public boolean isIdenticalValidatedPrivateDnses(@NonNull LinkProperties target) {
        Collection<InetAddress> targetDnses = target.getValidatedPrivateDnsServers();
        return (mValidatedPrivateDnses.size() == targetDnses.size())
                ? mValidatedPrivateDnses.containsAll(targetDnses) : false;
    }

    /**
     * Compares this {@code LinkProperties} PCSCF addresses against the target
     *
     * @param target LinkProperties to compare.
     * @return {@code true} if both are identical, {@code false} otherwise.
     * @hide
     */
    public boolean isIdenticalPcscfs(@NonNull LinkProperties target) {
        Collection<InetAddress> targetPcscfs = target.getPcscfServers();
        return (mPcscfs.size() == targetPcscfs.size()) ?
                    mPcscfs.containsAll(targetPcscfs) : false;
    }

    /**
     * Compares this {@code LinkProperties} Routes against the target
     *
     * @param target LinkProperties to compare.
     * @return {@code true} if both are identical, {@code false} otherwise.
     * @hide
     */
    @UnsupportedAppUsage
    public boolean isIdenticalRoutes(@NonNull LinkProperties target) {
        Collection<RouteInfo> targetRoutes = target.getRoutes();
        return (mRoutes.size() == targetRoutes.size()) ?
                mRoutes.containsAll(targetRoutes) : false;
    }

    /**
     * Compares this {@code LinkProperties} HttpProxy against the target
     *
     * @param target LinkProperties to compare.
     * @return {@code true} if both are identical, {@code false} otherwise.
     * @hide
     */
    @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
    public boolean isIdenticalHttpProxy(@NonNull LinkProperties target) {
        return getHttpProxy() == null ? target.getHttpProxy() == null :
                getHttpProxy().equals(target.getHttpProxy());
    }

    /**
     * Compares this {@code LinkProperties} stacked links against the target
     *
     * @param target LinkProperties to compare.
     * @return {@code true} if both are identical, {@code false} otherwise.
     * @hide
     */
    @UnsupportedAppUsage
    public boolean isIdenticalStackedLinks(@NonNull LinkProperties target) {
        if (!mStackedLinks.keySet().equals(target.mStackedLinks.keySet())) {
            return false;
        }
        for (LinkProperties stacked : mStackedLinks.values()) {
            // Hashtable values can never be null.
            String iface = stacked.getInterfaceName();
            if (!stacked.equals(target.mStackedLinks.get(iface))) {
                return false;
            }
        }
        return true;
    }

    /**
     * Compares this {@code LinkProperties} MTU against the target
     *
     * @param target LinkProperties to compare.
     * @return {@code true} if both are identical, {@code false} otherwise.
     * @hide
     */
    public boolean isIdenticalMtu(@NonNull LinkProperties target) {
        return getMtu() == target.getMtu();
    }

    /**
     * Compares this {@code LinkProperties} Tcp buffer sizes against the target.
     *
     * @param target LinkProperties to compare.
     * @return {@code true} if both are identical, {@code false} otherwise.
     * @hide
     */
    public boolean isIdenticalTcpBufferSizes(@NonNull LinkProperties target) {
        return Objects.equals(mTcpBufferSizes, target.mTcpBufferSizes);
    }

    /**
     * Compares this {@code LinkProperties} NAT64 prefix against the target.
     *
     * @param target LinkProperties to compare.
     * @return {@code true} if both are identical, {@code false} otherwise.
     * @hide
     */
    public boolean isIdenticalNat64Prefix(@NonNull LinkProperties target) {
        return Objects.equals(mNat64Prefix, target.mNat64Prefix);
    }

    /**
     * Compares this {@code LinkProperties} WakeOnLan supported against the target.
     *
     * @param target LinkProperties to compare.
     * @return {@code true} if both are identical, {@code false} otherwise.
     * @hide
     */
    public boolean isIdenticalWakeOnLan(LinkProperties target) {
        return isWakeOnLanSupported() == target.isWakeOnLanSupported();
    }

    /**
     * Set whether the network interface supports WakeOnLAN
     *
     * @param supported WakeOnLAN supported value
     *
     * @hide
     */
    public void setWakeOnLanSupported(boolean supported) {
        mWakeOnLanSupported = supported;
    }

    /**
     * Returns whether the network interface supports WakeOnLAN
     *
     * @return {@code true} if interface supports WakeOnLAN, {@code false} otherwise.
     */
    public boolean isWakeOnLanSupported() {
        return mWakeOnLanSupported;
    }

    /**
     * Compares this {@code LinkProperties} instance against the target
     * LinkProperties in {@code obj}. Two LinkPropertieses are equal if
     * all their fields are equal in values.
     *
     * For collection fields, such as mDnses, containsAll() is used to check
     * if two collections contains the same elements, independent of order.
     * There are two thoughts regarding containsAll()
     * 1. Duplicated elements. eg, (A, B, B) and (A, A, B) are equal.
     * 2. Worst case performance is O(n^2).
     *
     * @param obj the object to be tested for equality.
     * @return {@code true} if both objects are equal, {@code false} otherwise.
     */
    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;

        if (!(obj instanceof LinkProperties)) return false;

        LinkProperties target = (LinkProperties) obj;
        /*
         * This method does not check that stacked interfaces are equal, because
         * stacked interfaces are not so much a property of the link as a
         * description of connections between links.
         */
        return isIdenticalInterfaceName(target)
                && isIdenticalAddresses(target)
                && isIdenticalDnses(target)
                && isIdenticalPrivateDns(target)
                && isIdenticalValidatedPrivateDnses(target)
                && isIdenticalPcscfs(target)
                && isIdenticalRoutes(target)
                && isIdenticalHttpProxy(target)
                && isIdenticalStackedLinks(target)
                && isIdenticalMtu(target)
                && isIdenticalTcpBufferSizes(target)
                && isIdenticalNat64Prefix(target)
                && isIdenticalWakeOnLan(target);
    }

    /**
     * Compares the addresses in this LinkProperties with another
     * LinkProperties, examining only addresses on the base link.
     *
     * @param target a LinkProperties with the new list of addresses
     * @return the differences between the addresses.
     * @hide
     */
    public @NonNull CompareResult<LinkAddress> compareAddresses(@Nullable LinkProperties target) {
        /*
         * Duplicate the LinkAddresses into removed, we will be removing
         * address which are common between mLinkAddresses and target
         * leaving the addresses that are different. And address which
         * are in target but not in mLinkAddresses are placed in the
         * addedAddresses.
         */
        return new CompareResult<>(mLinkAddresses,
                target != null ? target.getLinkAddresses() : null);
    }

    /**
     * Compares the DNS addresses in this LinkProperties with another
     * LinkProperties, examining only DNS addresses on the base link.
     *
     * @param target a LinkProperties with the new list of dns addresses
     * @return the differences between the DNS addresses.
     * @hide
     */
    public @NonNull CompareResult<InetAddress> compareDnses(@Nullable LinkProperties target) {
        /*
         * Duplicate the InetAddresses into removed, we will be removing
         * dns address which are common between mDnses and target
         * leaving the addresses that are different. And dns address which
         * are in target but not in mDnses are placed in the
         * addedAddresses.
         */
        return new CompareResult<>(mDnses, target != null ? target.getDnsServers() : null);
    }

    /**
     * Compares the validated private DNS addresses in this LinkProperties with another
     * LinkProperties.
     *
     * @param target a LinkProperties with the new list of validated private dns addresses
     * @return the differences between the DNS addresses.
     * @hide
     */
    public @NonNull CompareResult<InetAddress> compareValidatedPrivateDnses(
            @Nullable LinkProperties target) {
        return new CompareResult<>(mValidatedPrivateDnses,
                target != null ? target.getValidatedPrivateDnsServers() : null);
    }

    /**
     * Compares all routes in this LinkProperties with another LinkProperties,
     * examining both the the base link and all stacked links.
     *
     * @param target a LinkProperties with the new list of routes
     * @return the differences between the routes.
     * @hide
     */
    public @NonNull CompareResult<RouteInfo> compareAllRoutes(@Nullable LinkProperties target) {
        /*
         * Duplicate the RouteInfos into removed, we will be removing
         * routes which are common between mRoutes and target
         * leaving the routes that are different. And route address which
         * are in target but not in mRoutes are placed in added.
         */
        return new CompareResult<>(getAllRoutes(), target != null ? target.getAllRoutes() : null);
    }

    /**
     * Compares all interface names in this LinkProperties with another
     * LinkProperties, examining both the the base link and all stacked links.
     *
     * @param target a LinkProperties with the new list of interface names
     * @return the differences between the interface names.
     * @hide
     */
    public @NonNull CompareResult<String> compareAllInterfaceNames(
            @Nullable LinkProperties target) {
        /*
         * Duplicate the interface names into removed, we will be removing
         * interface names which are common between this and target
         * leaving the interface names that are different. And interface names which
         * are in target but not in this are placed in added.
         */
        return new CompareResult<>(getAllInterfaceNames(),
                target != null ? target.getAllInterfaceNames() : null);
    }


    /**
     * Generate hashcode based on significant fields
     *
     * Equal objects must produce the same hash code, while unequal objects
     * may have the same hash codes.
     */
    @Override
    public int hashCode() {
        return ((null == mIfaceName) ? 0 : mIfaceName.hashCode()
                + mLinkAddresses.size() * 31
                + mDnses.size() * 37
                + mValidatedPrivateDnses.size() * 61
                + ((null == mDomains) ? 0 : mDomains.hashCode())
                + mRoutes.size() * 41
                + ((null == mHttpProxy) ? 0 : mHttpProxy.hashCode())
                + mStackedLinks.hashCode() * 47)
                + mMtu * 51
                + ((null == mTcpBufferSizes) ? 0 : mTcpBufferSizes.hashCode())
                + (mUsePrivateDns ? 57 : 0)
                + mPcscfs.size() * 67
                + ((null == mPrivateDnsServerName) ? 0 : mPrivateDnsServerName.hashCode())
                + Objects.hash(mNat64Prefix)
                + (mWakeOnLanSupported ? 71 : 0);
    }

    /**
     * Implement the Parcelable interface.
     */
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(getInterfaceName());
        dest.writeInt(mLinkAddresses.size());
        for (LinkAddress linkAddress : mLinkAddresses) {
            dest.writeParcelable(linkAddress, flags);
        }

        dest.writeInt(mDnses.size());
        for (InetAddress d : mDnses) {
            dest.writeByteArray(d.getAddress());
        }
        dest.writeInt(mValidatedPrivateDnses.size());
        for (InetAddress d : mValidatedPrivateDnses) {
            dest.writeByteArray(d.getAddress());
        }
        dest.writeBoolean(mUsePrivateDns);
        dest.writeString(mPrivateDnsServerName);
        dest.writeInt(mPcscfs.size());
        for (InetAddress d : mPcscfs) {
            dest.writeByteArray(d.getAddress());
        }
        dest.writeString(mDomains);
        dest.writeInt(mMtu);
        dest.writeString(mTcpBufferSizes);
        dest.writeInt(mRoutes.size());
        for (RouteInfo route : mRoutes) {
            dest.writeParcelable(route, flags);
        }

        if (mHttpProxy != null) {
            dest.writeByte((byte)1);
            dest.writeParcelable(mHttpProxy, flags);
        } else {
            dest.writeByte((byte)0);
        }
        dest.writeParcelable(mNat64Prefix, 0);

        ArrayList<LinkProperties> stackedLinks = new ArrayList<>(mStackedLinks.values());
        dest.writeList(stackedLinks);

        dest.writeBoolean(mWakeOnLanSupported);
    }

    /**
     * Implement the Parcelable interface.
     */
    public static final @android.annotation.NonNull Creator<LinkProperties> CREATOR =
        new Creator<LinkProperties>() {
            public LinkProperties createFromParcel(Parcel in) {
                LinkProperties netProp = new LinkProperties();

                String iface = in.readString();
                if (iface != null) {
                    netProp.setInterfaceName(iface);
                }
                int addressCount = in.readInt();
                for (int i = 0; i < addressCount; i++) {
                    netProp.addLinkAddress(in.readParcelable(null));
                }
                addressCount = in.readInt();
                for (int i = 0; i < addressCount; i++) {
                    try {
                        netProp.addDnsServer(InetAddress.getByAddress(in.createByteArray()));
                    } catch (UnknownHostException e) { }
                }
                addressCount = in.readInt();
                for (int i = 0; i < addressCount; i++) {
                    try {
                        netProp.addValidatedPrivateDnsServer(
                                InetAddress.getByAddress(in.createByteArray()));
                    } catch (UnknownHostException e) { }
                }
                netProp.setUsePrivateDns(in.readBoolean());
                netProp.setPrivateDnsServerName(in.readString());
                addressCount = in.readInt();
                for (int i = 0; i < addressCount; i++) {
                    try {
                        netProp.addPcscfServer(InetAddress.getByAddress(in.createByteArray()));
                    } catch (UnknownHostException e) { }
                }
                netProp.setDomains(in.readString());
                netProp.setMtu(in.readInt());
                netProp.setTcpBufferSizes(in.readString());
                addressCount = in.readInt();
                for (int i = 0; i < addressCount; i++) {
                    netProp.addRoute(in.readParcelable(null));
                }
                if (in.readByte() == 1) {
                    netProp.setHttpProxy(in.readParcelable(null));
                }
                netProp.setNat64Prefix(in.readParcelable(null));
                ArrayList<LinkProperties> stackedLinks = new ArrayList<LinkProperties>();
                in.readList(stackedLinks, LinkProperties.class.getClassLoader());
                for (LinkProperties stackedLink: stackedLinks) {
                    netProp.addStackedLink(stackedLink);
                }
                netProp.setWakeOnLanSupported(in.readBoolean());
                return netProp;
            }

            public LinkProperties[] newArray(int size) {
                return new LinkProperties[size];
            }
        };

    /**
     * Check the valid MTU range based on IPv4 or IPv6.
     * @hide
     */
    public static boolean isValidMtu(int mtu, boolean ipv6) {
        if (ipv6) {
            return mtu >= MIN_MTU_V6 && mtu <= MAX_MTU;
        } else {
            return mtu >= MIN_MTU && mtu <= MAX_MTU;
        }
    }
}