How can I catch the exception if IPV6 address is passed
-
27-05-2021 - |
Question
This is my below code and I want to catch the exception if any IPV6 address is passed. Any idea how it can be done in my code?
private static boolean validateAnIpAddress(String ipAddr) {
InetAddress address = null;
boolean isIPv4;
try {
address = InetAddress.getByName(ipAddr);
isIPv4 = address.getHostAddress().equals(ipAddr) && address instanceof Inet4Address;
} catch (UnknownHostException e) {
getLogger().log(LogLevel.ERROR, e.getMessage());
//return false;
isIPv4 = false;
}
return isIPv4;
}
Solution
try
{
address = InetAddress.getByName(ipAddr);
boolean isIPv6 = address instanceof Inet6Address;
if (isIPv6)
throw new UnknownHostException("IPv6 Address");
isIPv4 = address.getHostAddress().equals(ipAddr) && address instanceof Inet4Address;
}
By checking if address
is an Inet6Address
type, you can throw the exception inside the try
block and therefore triggering your catch
block.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow