diff options
author | Remi NGUYEN VAN <reminv@google.com> | 2021-03-16 14:12:24 +0900 |
---|---|---|
committer | Remi NGUYEN VAN <reminv@google.com> | 2021-03-16 14:31:45 +0900 |
commit | 7a7976fc57157032376ea5eba4300073dc4f3f66 (patch) | |
tree | 5a3d8245258bc40503e94cfa61e62048b1c7fd24 /common/framework | |
parent | ecb948964f8603d1b580cb49e087fb5b4831a435 (diff) | |
download | net-7a7976fc57157032376ea5eba4300073dc4f3f66.tar.gz |
Move trimV4AddrZeros to libs/net
The utility is @UnsupportedAppUsage, and also used by internal classes
like WifiTrackerLib or Mms, so it needs to be in a shared location.
Bug: 182859030
Test: atest NetworkStaticLibTests
Change-Id: Ia2be2ef62ea1e7dfdff1f54a14d8f2e282d36fca
Diffstat (limited to 'common/framework')
-rw-r--r-- | common/framework/com/android/net/module/util/Inet4AddressUtils.java | 26 |
1 files changed, 26 insertions, 0 deletions
diff --git a/common/framework/com/android/net/module/util/Inet4AddressUtils.java b/common/framework/com/android/net/module/util/Inet4AddressUtils.java index a1d34a0f..87f43d51 100644 --- a/common/framework/com/android/net/module/util/Inet4AddressUtils.java +++ b/common/framework/com/android/net/module/util/Inet4AddressUtils.java @@ -163,4 +163,30 @@ public class Inet4AddressUtils { throws IllegalArgumentException { return intToInet4AddressHTH(prefixLengthToV4NetmaskIntHTH(prefixLength)); } + + /** + * Trim leading zeros from IPv4 address strings + * Non-v4 addresses and host names remain unchanged. + * For example, 192.168.000.010 -> 192.168.0.10 + * @param addr a string representing an ip address + * @return a string properly trimmed + */ + public static String trimAddressZeros(String addr) { + if (addr == null) return null; + String[] octets = addr.split("\\."); + if (octets.length != 4) return addr; + StringBuilder builder = new StringBuilder(16); + String result = null; + for (int i = 0; i < 4; i++) { + try { + if (octets[i].length() > 3) return addr; + builder.append(Integer.parseInt(octets[i])); + } catch (NumberFormatException e) { + return addr; + } + if (i < 3) builder.append('.'); + } + result = builder.toString(); + return result; + } } |