Merge "Avoid random twice to generate an address" into main

This commit is contained in:
Mark Chien 2023-11-27 05:38:34 +00:00 • committed by Gerrit Code Review
commit 692643601d

View file

@ -79,6 +79,7 @@ public class PrivateAddressCoordinator {
private final TetheringConfiguration mConfig;
// keyed by downstream type(TetheringManager.TETHERING_*).
private final ArrayMap<AddressKey, LinkAddress> mCachedAddresses;
private final Random mRandom;
public PrivateAddressCoordinator(Context context, TetheringConfiguration config) {
mDownstreams = new ArraySet<>();
@ -95,6 +96,7 @@ public class PrivateAddressCoordinator {
mTetheringPrefixes = new ArrayList<>(Arrays.asList(new IpPrefix("192.168.0.0/16"),
new IpPrefix("172.16.0.0/12"), new IpPrefix("10.0.0.0/8")));
mRandom = new Random();
}
/**
@ -263,12 +265,13 @@ public class PrivateAddressCoordinator {
// is less than 127.0.0.0 = 0x7f000000 = 2130706432.
//
// Additionally, it makes debug output easier to read by making the numbers smaller.
final int randomPrefixStart = getRandomInt() & ~prefixRangeMask & prefixMask;
final int randomInt = getRandomInt();
final int randomPrefixStart = randomInt & ~prefixRangeMask & prefixMask;
// A random offset within the prefix. Used to determine the local address once the prefix
// is selected. It does not result in an IPv4 address ending in .0, .1, or .255
// For a PREFIX_LENGTH of 255, this is a number between 2 and 254.
final int subAddress = getSanitizedSubAddr(~prefixMask);
// For a PREFIX_LENGTH of 24, this is a number between 2 and 254.
final int subAddress = getSanitizedSubAddr(randomInt, ~prefixMask);
// Find a prefix length PREFIX_LENGTH between randomPrefixStart and the end of the block,
// such that the prefix does not conflict with any upstream.
@ -310,12 +313,12 @@ public class PrivateAddressCoordinator {
/** Get random int which could be used to generate random address. */
@VisibleForTesting
public int getRandomInt() {
return (new Random()).nextInt();
return mRandom.nextInt();
}
/** Get random subAddress and avoid selecting x.x.x.0, x.x.x.1 and x.x.x.255 address. */
private int getSanitizedSubAddr(final int subAddrMask) {
final int randomSubAddr = getRandomInt() & subAddrMask;
private int getSanitizedSubAddr(final int randomInt, final int subAddrMask) {
final int randomSubAddr = randomInt & subAddrMask;
// If prefix length > 30, the selecting speace would be less than 4 which may be hard to
// avoid 3 consecutive address.
if (PREFIX_LENGTH > 30) return randomSubAddr;