Let `isInetAddress` utility understand the scope ID on ipv6 (#60172) (#60263)

Make `isInetAddress` utility method understand the scope ID on ipv6.

Fixes #60115

Co-authored-by: Yang Cheng <chengyang2048@163.com>
This commit is contained in:
Armin Braun 2020-07-28 09:37:39 +02:00 committed by GitHub
parent aba785cb6e
commit fac5953d13
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 22 additions and 0 deletions

View File

@ -38,6 +38,7 @@ public class InetAddresses {
// Make a first pass to categorize the characters in this string.
boolean hasColon = false;
boolean hasDot = false;
int percentIndex = -1;
for (int i = 0; i < ipString.length(); i++) {
char c = ipString.charAt(i);
if (c == '.') {
@ -47,6 +48,9 @@ public class InetAddresses {
return null; // Colons must not appear after dots.
}
hasColon = true;
} else if (c == '%') {
percentIndex = i;
break; // Everything after a '%' is ignored (it's a Scope ID)
} else if (Character.digit(c, 16) == -1) {
return null; // Everything else must be a decimal or hex digit.
}
@ -60,6 +64,12 @@ public class InetAddresses {
return null;
}
}
if (percentIndex == ipString.length() - 1) {
return null; // Filter out strings that end in % and have an empty scope ID.
}
if (percentIndex != -1) {
ipString = ipString.substring(0, percentIndex);
}
return textToNumericFormatV6(ipString);
} else if (hasDot) {
return textToNumericFormatV4(ipString);

View File

@ -128,6 +128,18 @@ public class InetAddressesTests extends ESTestCase {
assertTrue(InetAddresses.isInetAddress(ipStr));
}
public void testForStringIPv6WithScopeIdInput() throws UnknownHostException {
String ipStr = "0:0:0:0:0:0:0:1%lo";
InetAddress ipv6Addr = InetAddress.getByName(ipStr);
assertEquals(ipv6Addr, InetAddresses.forString(ipStr));
assertTrue(InetAddresses.isInetAddress(ipStr));
}
public void testForStringIPv6WithInvalidScopeIdInput() {
String ipStr = "0:0:0:0:0:0:0:1%";
assertFalse(InetAddresses.isInetAddress(ipStr));
}
public void testForStringIPv6EightColons() throws UnknownHostException {
String[] eightColons = {
"::7:6:5:4:3:2:1",