Path: blob/master/src/java.base/share/classes/sun/net/util/IPAddressUtil.java
67770 views
/*1* Copyright (c) 2004, 2022, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package sun.net.util;2627import sun.security.action.GetPropertyAction;2829import java.io.UncheckedIOException;30import java.net.Inet6Address;31import java.net.InetAddress;32import java.net.InetSocketAddress;33import java.net.NetworkInterface;34import java.net.SocketException;35import java.net.URL;36import java.nio.CharBuffer;37import java.security.AccessController;38import java.security.PrivilegedExceptionAction;39import java.security.PrivilegedActionException;40import java.util.Arrays;41import java.util.List;42import java.util.concurrent.ConcurrentHashMap;4344public class IPAddressUtil {45private static final int INADDR4SZ = 4;46private static final int INADDR16SZ = 16;47private static final int INT16SZ = 2;4849/*50* Converts IPv4 address in its textual presentation form51* into its numeric binary form.52*53* @param src a String representing an IPv4 address in standard format54* @return a byte array representing the IPv4 numeric address55*/56@SuppressWarnings("fallthrough")57public static byte[] textToNumericFormatV4(String src)58{59byte[] res = new byte[INADDR4SZ];6061long tmpValue = 0;62int currByte = 0;63boolean newOctet = true;6465int len = src.length();66if (len == 0 || len > 15) {67return null;68}69/*70* When only one part is given, the value is stored directly in71* the network address without any byte rearrangement.72*73* When a two part address is supplied, the last part is74* interpreted as a 24-bit quantity and placed in the right75* most three bytes of the network address. This makes the76* two part address format convenient for specifying Class A77* network addresses as net.host.78*79* When a three part address is specified, the last part is80* interpreted as a 16-bit quantity and placed in the right81* most two bytes of the network address. This makes the82* three part address format convenient for specifying83* Class B net- work addresses as 128.net.host.84*85* When four parts are specified, each is interpreted as a86* byte of data and assigned, from left to right, to the87* four bytes of an IPv4 address.88*89* We determine and parse the leading parts, if any, as single90* byte values in one pass directly into the resulting byte[],91* then the remainder is treated as a 8-to-32-bit entity and92* translated into the remaining bytes in the array.93*/94for (int i = 0; i < len; i++) {95char c = src.charAt(i);96if (c == '.') {97if (newOctet || tmpValue < 0 || tmpValue > 0xff || currByte == 3) {98return null;99}100res[currByte++] = (byte) (tmpValue & 0xff);101tmpValue = 0;102newOctet = true;103} else {104int digit = digit(c, 10);105if (digit < 0) {106return null;107}108tmpValue *= 10;109tmpValue += digit;110newOctet = false;111}112}113if (newOctet || tmpValue < 0 || tmpValue >= (1L << ((4 - currByte) * 8))) {114return null;115}116switch (currByte) {117case 0:118res[0] = (byte) ((tmpValue >> 24) & 0xff);119case 1:120res[1] = (byte) ((tmpValue >> 16) & 0xff);121case 2:122res[2] = (byte) ((tmpValue >> 8) & 0xff);123case 3:124res[3] = (byte) ((tmpValue >> 0) & 0xff);125}126return res;127}128129/**130* Validates if input string is a valid IPv4 address literal.131* If the "jdk.net.allowAmbiguousIPAddressLiterals" system property is set132* to {@code false}, or is not set then validation of the address string is performed as follows:133* If string can't be parsed by following IETF IPv4 address string literals134* formatting style rules (default one), but can be parsed by following BSD formatting135* style rules, the IPv4 address string content is treated as ambiguous and136* {@code IllegalArgumentException} is thrown.137*138* @param src input string139* @return bytes array if string is a valid IPv4 address string140* @throws IllegalArgumentException if "jdk.net.allowAmbiguousIPAddressLiterals" SP is set to141* "false" and IPv4 address string {@code "src"} is ambiguous142*/143public static byte[] validateNumericFormatV4(String src) {144byte[] parsedBytes = textToNumericFormatV4(src);145if (!ALLOW_AMBIGUOUS_IPADDRESS_LITERALS_SP_VALUE146&& parsedBytes == null && isBsdParsableV4(src)) {147throw new IllegalArgumentException("Invalid IP address literal: " + src);148}149return parsedBytes;150}151152/*153* Convert IPv6 presentation level address to network order binary form.154* credit:155* Converted from C code from Solaris 8 (inet_pton)156*157* Any component of the string following a per-cent % is ignored.158*159* @param src a String representing an IPv6 address in textual format160* @return a byte array representing the IPv6 numeric address161*/162public static byte[] textToNumericFormatV6(String src)163{164// Shortest valid string is "::", hence at least 2 chars165if (src.length() < 2) {166return null;167}168169int colonp;170char ch;171boolean saw_xdigit;172int val;173char[] srcb = src.toCharArray();174byte[] dst = new byte[INADDR16SZ];175176int srcb_length = srcb.length;177int pc = src.indexOf ('%');178if (pc == srcb_length -1) {179return null;180}181182if (pc != -1) {183srcb_length = pc;184}185186colonp = -1;187int i = 0, j = 0;188/* Leading :: requires some special handling. */189if (srcb[i] == ':')190if (srcb[++i] != ':')191return null;192int curtok = i;193saw_xdigit = false;194val = 0;195while (i < srcb_length) {196ch = srcb[i++];197int chval = digit(ch, 16);198if (chval != -1) {199val <<= 4;200val |= chval;201if (val > 0xffff)202return null;203saw_xdigit = true;204continue;205}206if (ch == ':') {207curtok = i;208if (!saw_xdigit) {209if (colonp != -1)210return null;211colonp = j;212continue;213} else if (i == srcb_length) {214return null;215}216if (j + INT16SZ > INADDR16SZ)217return null;218dst[j++] = (byte) ((val >> 8) & 0xff);219dst[j++] = (byte) (val & 0xff);220saw_xdigit = false;221val = 0;222continue;223}224if (ch == '.' && ((j + INADDR4SZ) <= INADDR16SZ)) {225String ia4 = src.substring(curtok, srcb_length);226/* check this IPv4 address has 3 dots, i.e. A.B.C.D */227int dot_count = 0, index=0;228while ((index = ia4.indexOf ('.', index)) != -1) {229dot_count ++;230index ++;231}232if (dot_count != 3) {233return null;234}235byte[] v4addr = textToNumericFormatV4(ia4);236if (v4addr == null) {237return null;238}239for (int k = 0; k < INADDR4SZ; k++) {240dst[j++] = v4addr[k];241}242saw_xdigit = false;243break; /* '\0' was seen by inet_pton4(). */244}245return null;246}247if (saw_xdigit) {248if (j + INT16SZ > INADDR16SZ)249return null;250dst[j++] = (byte) ((val >> 8) & 0xff);251dst[j++] = (byte) (val & 0xff);252}253254if (colonp != -1) {255int n = j - colonp;256257if (j == INADDR16SZ)258return null;259for (i = 1; i <= n; i++) {260dst[INADDR16SZ - i] = dst[colonp + n - i];261dst[colonp + n - i] = 0;262}263j = INADDR16SZ;264}265if (j != INADDR16SZ)266return null;267byte[] newdst = convertFromIPv4MappedAddress(dst);268if (newdst != null) {269return newdst;270} else {271return dst;272}273}274275/**276* @param src a String representing an IPv4 address in textual format277* @return a boolean indicating whether src is an IPv4 literal address278*/279public static boolean isIPv4LiteralAddress(String src) {280return textToNumericFormatV4(src) != null;281}282283/**284* @param src a String representing an IPv6 address in textual format285* @return a boolean indicating whether src is an IPv6 literal address286*/287public static boolean isIPv6LiteralAddress(String src) {288return textToNumericFormatV6(src) != null;289}290291/*292* Convert IPv4-Mapped address to IPv4 address. Both input and293* returned value are in network order binary form.294*295* @param src a String representing an IPv4-Mapped address in textual format296* @return a byte array representing the IPv4 numeric address297*/298public static byte[] convertFromIPv4MappedAddress(byte[] addr) {299if (isIPv4MappedAddress(addr)) {300byte[] newAddr = new byte[INADDR4SZ];301System.arraycopy(addr, 12, newAddr, 0, INADDR4SZ);302return newAddr;303}304return null;305}306307/**308* Utility routine to check if the InetAddress is an309* IPv4 mapped IPv6 address.310*311* @return a <code>boolean</code> indicating if the InetAddress is312* an IPv4 mapped IPv6 address; or false if address is IPv4 address.313*/314private static boolean isIPv4MappedAddress(byte[] addr) {315if (addr.length < INADDR16SZ) {316return false;317}318if ((addr[0] == 0x00) && (addr[1] == 0x00) &&319(addr[2] == 0x00) && (addr[3] == 0x00) &&320(addr[4] == 0x00) && (addr[5] == 0x00) &&321(addr[6] == 0x00) && (addr[7] == 0x00) &&322(addr[8] == 0x00) && (addr[9] == 0x00) &&323(addr[10] == (byte)0xff) &&324(addr[11] == (byte)0xff)) {325return true;326}327return false;328}329/**330* Mapping from unscoped local Inet(6)Address to the same address331* including the correct scope-id, determined from NetworkInterface.332*/333private static final ConcurrentHashMap<InetAddress,InetAddress>334cache = new ConcurrentHashMap<>();335336/**337* Returns a scoped version of the supplied local, link-local ipv6 address338* if that scope-id can be determined from local NetworkInterfaces.339* If the address already has a scope-id or if the address is not local, ipv6340* or link local, then the original address is returned.341*342* @param address343* @exception SocketException if the given ipv6 link local address is found344* on more than one local interface345* @return346*/347public static InetAddress toScopedAddress(InetAddress address)348throws SocketException {349350if (address instanceof Inet6Address && address.isLinkLocalAddress()351&& ((Inet6Address) address).getScopeId() == 0) {352353InetAddress cached = null;354try {355cached = cache.computeIfAbsent(address, k -> findScopedAddress(k));356} catch (UncheckedIOException e) {357throw (SocketException)e.getCause();358}359return cached != null ? cached : address;360} else {361return address;362}363}364365/**366* Same as above for InetSocketAddress367*/368public static InetSocketAddress toScopedAddress(InetSocketAddress address)369throws SocketException {370InetAddress addr;371InetAddress orig = address.getAddress();372if ((addr = toScopedAddress(orig)) == orig) {373return address;374} else {375return new InetSocketAddress(addr, address.getPort());376}377}378379@SuppressWarnings("removal")380private static InetAddress findScopedAddress(InetAddress address) {381PrivilegedExceptionAction<List<InetAddress>> pa = () -> NetworkInterface.networkInterfaces()382.flatMap(NetworkInterface::inetAddresses)383.filter(a -> (a instanceof Inet6Address)384&& address.equals(a)385&& ((Inet6Address) a).getScopeId() != 0)386.toList();387List<InetAddress> result;388try {389result = AccessController.doPrivileged(pa);390var sz = result.size();391if (sz == 0)392return null;393if (sz > 1)394throw new UncheckedIOException(new SocketException(395"Duplicate link local addresses: must specify scope-id"));396return result.get(0);397} catch (PrivilegedActionException pae) {398return null;399}400}401402// See java.net.URI for more details on how to generate these403// masks.404//405// square brackets406private static final long L_IPV6_DELIMS = 0x0L; // "[]"407private static final long H_IPV6_DELIMS = 0x28000000L; // "[]"408// RFC 3986 gen-delims409private static final long L_GEN_DELIMS = 0x8400800800000000L; // ":/?#[]@"410private static final long H_GEN_DELIMS = 0x28000001L; // ":/?#[]@"411// These gen-delims can appear in authority412private static final long L_AUTH_DELIMS = 0x400000000000000L; // "@[]:"413private static final long H_AUTH_DELIMS = 0x28000001L; // "@[]:"414// colon is allowed in userinfo415private static final long L_COLON = 0x400000000000000L; // ":"416private static final long H_COLON = 0x0L; // ":"417// slash should be encoded in authority418private static final long L_SLASH = 0x800000000000L; // "/"419private static final long H_SLASH = 0x0L; // "/"420// backslash should always be encoded421private static final long L_BACKSLASH = 0x0L; // "\"422private static final long H_BACKSLASH = 0x10000000L; // "\"423// ASCII chars 0-31 + 127 - various controls + CRLF + TAB424private static final long L_NON_PRINTABLE = 0xffffffffL;425private static final long H_NON_PRINTABLE = 0x8000000000000000L;426// All of the above427private static final long L_EXCLUDE = 0x84008008ffffffffL;428private static final long H_EXCLUDE = 0x8000000038000001L;429430private static final char[] OTHERS = {4318263,8264,8265,8448,8449,8453,8454,10868,43265109,65110,65119,65131,65283,65295,65306,65311,65312433};434435// Tell whether the given character is found by the given mask pair436public static boolean match(char c, long lowMask, long highMask) {437if (c < 64)438return ((1L << c) & lowMask) != 0;439if (c < 128)440return ((1L << (c - 64)) & highMask) != 0;441return false; // other non ASCII characters are not filtered442}443444// returns -1 if the string doesn't contain any characters445// from the mask, the index of the first such character found446// otherwise.447public static int scan(String s, long lowMask, long highMask) {448int i = -1, len;449if (s == null || (len = s.length()) == 0) return -1;450boolean match = false;451while (++i < len && !(match = match(s.charAt(i), lowMask, highMask)));452if (match) return i;453return -1;454}455456public static int scan(String s, long lowMask, long highMask, char[] others) {457int i = -1, len;458if (s == null || (len = s.length()) == 0) return -1;459boolean match = false;460char c, c0 = others[0];461while (++i < len && !(match = match((c=s.charAt(i)), lowMask, highMask))) {462if (c >= c0 && (Arrays.binarySearch(others, c) > -1)) {463match = true; break;464}465}466if (match) return i;467468return -1;469}470471private static String describeChar(char c) {472if (c < 32 || c == 127) {473if (c == '\n') return "LF";474if (c == '\r') return "CR";475return "control char (code=" + (int)c + ")";476}477if (c == '\\') return "'\\'";478return "'" + c + "'";479}480481private static String checkUserInfo(String str) {482// colon is permitted in user info483int index = scan(str, L_EXCLUDE & ~L_COLON,484H_EXCLUDE & ~H_COLON);485if (index >= 0) {486return "Illegal character found in user-info: "487+ describeChar(str.charAt(index));488}489return null;490}491492private static String checkHost(String str) {493int index;494if (str.startsWith("[") && str.endsWith("]")) {495str = str.substring(1, str.length() - 1);496if (isIPv6LiteralAddress(str)) {497index = str.indexOf('%');498if (index >= 0) {499index = scan(str = str.substring(index),500L_NON_PRINTABLE | L_IPV6_DELIMS,501H_NON_PRINTABLE | H_IPV6_DELIMS);502if (index >= 0) {503return "Illegal character found in IPv6 scoped address: "504+ describeChar(str.charAt(index));505}506}507return null;508}509return "Unrecognized IPv6 address format";510} else {511index = scan(str, L_EXCLUDE, H_EXCLUDE);512if (index >= 0) {513return "Illegal character found in host: "514+ describeChar(str.charAt(index));515}516}517return null;518}519520private static String checkAuth(String str) {521int index = scan(str,522L_EXCLUDE & ~L_AUTH_DELIMS,523H_EXCLUDE & ~H_AUTH_DELIMS);524if (index >= 0) {525return "Illegal character found in authority: "526+ describeChar(str.charAt(index));527}528return null;529}530531// check authority of hierarchical URL. Appropriate for532// HTTP-like protocol handlers533public static String checkAuthority(URL url) {534String s, u, h;535if (url == null) return null;536if ((s = checkUserInfo(u = url.getUserInfo())) != null) {537return s;538}539if ((s = checkHost(h = url.getHost())) != null) {540return s;541}542if (h == null && u == null) {543return checkAuth(url.getAuthority());544}545return null;546}547548// minimal syntax checks - deeper check may be performed549// by the appropriate protocol handler550public static String checkExternalForm(URL url) {551String s;552if (url == null) return null;553int index = scan(s = url.getUserInfo(),554L_NON_PRINTABLE | L_SLASH,555H_NON_PRINTABLE | H_SLASH);556if (index >= 0) {557return "Illegal character found in authority: "558+ describeChar(s.charAt(index));559}560if ((s = checkHostString(url.getHost())) != null) {561return s;562}563return null;564}565566public static String checkHostString(String host) {567if (host == null) return null;568int index = scan(host,569L_NON_PRINTABLE | L_SLASH,570H_NON_PRINTABLE | H_SLASH,571OTHERS);572if (index >= 0) {573return "Illegal character found in host: "574+ describeChar(host.charAt(index));575}576return null;577}578579/**580* Returns the numeric value of the character {@code ch} in the581* specified radix.582*583* @param ch the character to be converted.584* @param radix the radix.585* @return the numeric value represented by the character in the586* specified radix.587*/588public static int digit(char ch, int radix) {589if (ALLOW_AMBIGUOUS_IPADDRESS_LITERALS_SP_VALUE) {590return Character.digit(ch, radix);591} else {592return parseAsciiDigit(ch, radix);593}594}595596/**597* Try to parse String as IPv4 address literal by following598* BSD-style formatting rules.599*600* @param input input string601* @return {@code true} if input string is parsable as IPv4 address literal,602* {@code false} otherwise.603*/604public static boolean isBsdParsableV4(String input) {605char firstSymbol = input.charAt(0);606// Check if first digit is not a decimal digit607if (parseAsciiDigit(firstSymbol, DECIMAL) == -1) {608return false;609}610611// Last character is dot OR is not a supported digit: [0-9,A-F,a-f]612char lastSymbol = input.charAt(input.length() - 1);613if (lastSymbol == '.' || parseAsciiHexDigit(lastSymbol) == -1) {614return false;615}616617// Parse IP address fields618CharBuffer charBuffer = CharBuffer.wrap(input);619int fieldNumber = 0;620while (charBuffer.hasRemaining()) {621long fieldValue = -1L;622// Try to parse fields in all supported radixes623for (int radix : SUPPORTED_RADIXES) {624fieldValue = parseV4FieldBsd(radix, charBuffer, fieldNumber);625if (fieldValue >= 0) {626fieldNumber++;627break;628} else if (fieldValue == TERMINAL_PARSE_ERROR) {629return false;630}631}632// If field can't be parsed as one of supported radixes stop633// parsing634if (fieldValue < 0) {635return false;636}637}638return true;639}640641/**642* Method tries to parse IP address field that starts from {@linkplain CharBuffer#position()643* current position} of the provided character buffer.644* <p>645* This method supports three {@code "radix"} values to decode field values in646* {@code "HEXADECIMAL (radix=16)"}, {@code "DECIMAL (radix=10)"} and647* {@code "OCTAL (radix=8)"} radixes.648* <p>649* If {@code -1} value is returned the char buffer position is reset to the value650* it was before it was called.651* <p>652* Method returns {@code -2} if formatting illegal for all supported {@code radix}653* values is observed, and there is no point in checking other radix values.654* That includes the following cases:<ul>655* <li>Two subsequent dots are observer656* <li>Number of dots more than 3657* <li>Field value exceeds max allowed658* <li>Character is not a valid digit for the requested {@code radix} value, given659* that a field has the radix specific prefix660* </ul>661*662* @param radix digits encoding radix to use for parsing. Valid values: 8, 10, 16.663* @param buffer {@code CharBuffer} with position set to the field's fist character664* @param fieldNumber parsed field number665* @return {@code CANT_PARSE_IN_RADIX} if field can not be parsed in requested {@code radix}.666* {@code TERMINAL_PARSE_ERROR} if field can't be parsed and the whole parse process should be terminated.667* Parsed field value otherwise.668*/669private static long parseV4FieldBsd(int radix, CharBuffer buffer, int fieldNumber) {670int initialPos = buffer.position();671long val = 0;672int digitsCount = 0;673if (!checkPrefix(buffer, radix)) {674val = CANT_PARSE_IN_RADIX;675}676boolean dotSeen = false;677while (buffer.hasRemaining() && val != CANT_PARSE_IN_RADIX && !dotSeen) {678char c = buffer.get();679if (c == '.') {680dotSeen = true;681// Fail if 4 dots in IP address string.682// fieldNumber counter starts from 0, therefore 3683if (fieldNumber == 3) {684// Terminal state, can stop parsing: too many fields685return TERMINAL_PARSE_ERROR;686}687// Check for literals with two dots, like '1.2..3', '1.2.3..'688if (digitsCount == 0) {689// Terminal state, can stop parsing: dot with no digits690return TERMINAL_PARSE_ERROR;691}692if (val > 255) {693// Terminal state, can stop parsing: too big value for an octet694return TERMINAL_PARSE_ERROR;695}696} else {697int dv = parseAsciiDigit(c, radix);698if (dv >= 0) {699digitsCount++;700val *= radix;701val += dv;702} else {703// Spotted digit can't be parsed in the requested 'radix'.704// The order in which radixes are checked - hex, octal, decimal:705// - if symbol is not a valid digit in hex radix - terminal706// - if symbol is not a valid digit in octal radix, and given707// that octal prefix was observed before - terminal708// - if symbol is not a valid digit in decimal radix - terminal709return TERMINAL_PARSE_ERROR;710}711}712}713if (val == CANT_PARSE_IN_RADIX) {714buffer.position(initialPos);715} else if (!dotSeen) {716// It is the last field - check its value717// This check will ensure that address strings with less718// than 4 fields, i.e. A, A.B and A.B.C address types719// contain value less then the allowed maximum for the last field.720long maxValue = (1L << ((4 - fieldNumber) * 8)) - 1;721if (val > maxValue) {722// Terminal state, can stop parsing: last field value exceeds its723// allowed value724return TERMINAL_PARSE_ERROR;725}726}727return val;728}729730// This method moves the position of the supplied CharBuffer by analysing the digit prefix731// symbols if any.732// The caller should reset the position when method returns false.733private static boolean checkPrefix(CharBuffer buffer, int radix) {734return switch (radix) {735case OCTAL -> isOctalFieldStart(buffer);736case DECIMAL -> isDecimalFieldStart(buffer);737case HEXADECIMAL -> isHexFieldStart(buffer);738default -> throw new AssertionError("Not supported radix");739};740}741742// This method always moves the position of the supplied CharBuffer743// removing the octal prefix symbols '0'.744// The caller should reset the position when method returns false.745private static boolean isOctalFieldStart(CharBuffer cb) {746// .0<EOS> is not treated as octal field747if (cb.remaining() < 2) {748return false;749}750751// Fetch two first characters752int position = cb.position();753char first = cb.get();754char second = cb.get();755756// Return false if the first char is not octal prefix '0' or second is a757// field separator - parseV4FieldBsd will reset position to start of the field.758// '.0.' fields will be successfully parsed in decimal radix.759boolean isOctalPrefix = first == '0' && second != '.';760761// If the prefix looks like octal - consume '0', otherwise 'false' is returned762// and caller will reset the buffer position.763if (isOctalPrefix) {764cb.position(position + 1);765}766return isOctalPrefix;767}768769// This method doesn't move the position of the supplied CharBuffer770private static boolean isDecimalFieldStart(CharBuffer cb) {771return cb.hasRemaining();772}773774// This method always moves the position of the supplied CharBuffer775// removing the hexadecimal prefix symbols '0x'.776// The caller should reset the position when method returns false.777private static boolean isHexFieldStart(CharBuffer cb) {778if (cb.remaining() < 2) {779return false;780}781char first = cb.get();782char second = cb.get();783return first == '0' && (second == 'x' || second == 'X');784}785786// Parse ASCII digit in given radix787private static int parseAsciiDigit(char c, int radix) {788assert radix == OCTAL || radix == DECIMAL || radix == HEXADECIMAL;789if (radix == HEXADECIMAL) {790return parseAsciiHexDigit(c);791}792int val = c - '0';793return (val < 0 || val >= radix) ? -1 : val;794}795796// Parse ASCII digit in hexadecimal radix797private static int parseAsciiHexDigit(char digit) {798char c = Character.toLowerCase(digit);799if (c >= 'a' && c <= 'f') {800return c - 'a' + 10;801}802return parseAsciiDigit(c, DECIMAL);803}804805// Supported radixes806private static final int HEXADECIMAL = 16;807private static final int DECIMAL = 10;808private static final int OCTAL = 8;809// Order in which field formats are exercised to parse one IP address textual field810private static final int[] SUPPORTED_RADIXES = new int[]{HEXADECIMAL, OCTAL, DECIMAL};811812// BSD parser's return values813private final static long CANT_PARSE_IN_RADIX = -1L;814private final static long TERMINAL_PARSE_ERROR = -2L;815816private static final String ALLOW_AMBIGUOUS_IPADDRESS_LITERALS_SP = "jdk.net.allowAmbiguousIPAddressLiterals";817private static final boolean ALLOW_AMBIGUOUS_IPADDRESS_LITERALS_SP_VALUE = Boolean.valueOf(818GetPropertyAction.privilegedGetProperty(ALLOW_AMBIGUOUS_IPADDRESS_LITERALS_SP, "false"));819}820821822