From 86a570287f3eccecf12fc0f74304cf28cdd8d88f Mon Sep 17 00:00:00 2001 From: Robert Greenwalt Date: Wed, 7 Dec 2011 09:58:48 -0800 Subject: [PATCH] Trim leading zeros from ipv4 addrs. Underlying libraries will interpret leading zeros as octal values and fail. bug:5262995 Change-Id: Iff949225bb6b941f7274ee81754e1f41ed719a6c --- core/java/android/net/NetworkUtils.java | 27 +++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/core/java/android/net/NetworkUtils.java b/core/java/android/net/NetworkUtils.java index e289fc15d0..72ea02e92e 100644 --- a/core/java/android/net/NetworkUtils.java +++ b/core/java/android/net/NetworkUtils.java @@ -250,4 +250,31 @@ public class NetworkUtils { } return result; } + + /** + * Trim leading zeros from IPv4 address strings + * Our base libraries will interpret that as octel.. + * Must leave non v4 addresses and host names alone. + * For example, 192.168.000.010 -> 192.168.0.10 + * TODO - fix base libraries and remove this function + * @param addr a string representing an ip addr + * @return a string propertly trimmed + */ + public static String trimV4AddrZeros(String addr) { + 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; + } }