Proof of concept URIUtil.isHostName

This commit is contained in:
Joakim Erdfelt 2023-04-19 14:38:22 -05:00
parent 43e8c83e24
commit ad5f8c4d15
No known key found for this signature in database
GPG Key ID: 2D0E1FB8FE4B68B4
2 changed files with 31 additions and 0 deletions

View File

@ -29,6 +29,7 @@ import java.util.List;
import java.util.Objects;
import java.util.StringTokenizer;
import java.util.function.Supplier;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import org.eclipse.jetty.util.resource.ResourceFactory;
@ -1315,6 +1316,21 @@ public final class URIUtil
return false;
}
/**
* Test if the token is a valid hostname and not an IP-Literal.
*
* @param token the token to check
* @return true if token is a Host name, not an IP-Literal
*/
public static boolean isHostName(String token)
{
Pattern patIPv4 = Pattern.compile("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}");
if (patIPv4.matcher(token).matches())
return false;
else
return isValidHostRegisteredName(token);
}
/**
* True if token is a <a href="https://www.rfc-editor.org/rfc/rfc3986">RFC3986</a> {@code reg-name} (Registered Name)
*

View File

@ -34,6 +34,7 @@ import org.junit.jupiter.api.condition.OS;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
@ -893,6 +894,20 @@ public class URIUtilTest
assertEquals(path, decoded);
}
@ParameterizedTest
@CsvSource(textBlock = """
127.0.0.1 , false
::1 , false
[::1] , false
localhost , true
localhost.local , true
sub.example.com , true
""")
public void testIsHostName(String token, boolean expected)
{
assertEquals(expected, URIUtil.isHostName(token));
}
@ParameterizedTest
@ValueSource(strings = {
"a",