/** * check if the literal address string has %nn appended returns -1 if not, or the numeric value * otherwise. * * <p>%nn may also be a string that represents the displayName of a currently available * NetworkInterface. */ private static int checkNumericZone(String s) throws UnknownHostException { int percent = s.indexOf('%'); int slen = s.length(); int digit, zone = 0; if (percent == -1) { return -1; } for (int i = percent + 1; i < slen; i++) { char c = s.charAt(i); if (c == ']') { if (i == percent + 1) { /* empty per-cent field */ return -1; } break; } if ((digit = Character.digit(c, 10)) < 0) { return -1; } zone = (zone * 10) + digit; } return zone; }
private static InetAddress[] getAllByName(String host, InetAddress reqAddr) throws UnknownHostException { if (host == null || host.length() == 0) { InetAddress[] ret = new InetAddress[1]; ret[0] = impl.loopbackAddress(); return ret; } boolean ipv6Expected = false; if (host.charAt(0) == '[') { // This is supposed to be an IPv6 litteral if (host.length() > 2 && host.charAt(host.length() - 1) == ']') { host = host.substring(1, host.length() - 1); ipv6Expected = true; } else { // This was supposed to be a IPv6 address, but it's not! throw new UnknownHostException(host); } } // if host is an IP address, we won't do further lookup if (Character.digit(host.charAt(0), 16) != -1 || (host.charAt(0) == ':')) { byte[] addr = null; int numericZone = -1; String ifname = null; // see if it is IPv4 address addr = IPAddressUtil.textToNumericFormatV4(host); if (addr == null) { // see if it is IPv6 address // Check if a numeric or string zone id is present int pos; if ((pos = host.indexOf("%")) != -1) { numericZone = checkNumericZone(host); if (numericZone == -1) { /* remainder of string must be an ifname */ ifname = host.substring(pos + 1); } } addr = IPAddressUtil.textToNumericFormatV6(host); } else if (ipv6Expected) { // Means an IPv4 litteral between brackets! throw new UnknownHostException("[" + host + "]"); } InetAddress[] ret = new InetAddress[1]; if (addr != null) { if (addr.length == Inet4Address.INADDRSZ) { ret[0] = new Inet4Address(null, addr); } else { if (ifname != null) { ret[0] = new Inet6Address(null, addr, ifname); } else { ret[0] = new Inet6Address(null, addr, numericZone); } } return ret; } } else if (ipv6Expected) { // We were expecting an IPv6 Litteral, but got something else throw new UnknownHostException("[" + host + "]"); } return getAllByName0(host, reqAddr, true); }