Created class to validate ipv4/6 address and port.

This commit is contained in:
WickedJack99
2023-12-05 15:35:34 +01:00
parent 29f33fc5de
commit 8f0c9067fb

View File

@@ -0,0 +1,69 @@
/**
* @author Aaron Moser
* @date 05.12.2023
*/
package controller.src.Validate;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Validate {
/**
* Checks if overhanded string is valid ip address, by checking if its length is 13 or less,
* it contains exactly 4 numbers and if the numbers are in valid range.
* @param ipv4Address
* @return
*/
public static boolean isValidIPv4Address(String ipv4Address) {
boolean isValidIPv4Address = false;
// Maximum length of ipv4 address is 13 characters, only evaluate if
// length of string is less or equal to 13.
if (ipv4Address.length() <= 13) {
String[] numbersAsString = ipv4Address.split(".");
// If ip address contains exactly 4 parts splitted by dots:
if (numbersAsString.length == 4) {
// Transform each part to integer and check if in valid range.
for (String numberAsString : numbersAsString) {
int number = Integer.valueOf(numberAsString);
if (number < 0 || number > 255) {
isValidIPv4Address = false;
break;
}
}
isValidIPv4Address = true;
} else {
isValidIPv4Address = false;
}
}
return isValidIPv4Address;
}
/**
* Checks if overhanded ipv6 address is valid by applying a regex to it.
* @param ipv6Address
* @return
*/
public static boolean isValidIPv6Address(String ipv6Address) {
Pattern pattern = Pattern.compile("^([0-9a-f]{4}:){7}[0-9a-f]{4}$", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(ipv6Address);
boolean matchFound = matcher.find();
if(matchFound) {
return true;
} else {
return false;
}
}
/**
* Port is validated by checking if in bounds of overhanded values.
* @param port
* @param startOfRange
* @param endOfRange
* @return
*/
public static boolean isValidPort(String port, int startOfRange, int endOfRange) {
int portAsInt = Integer.valueOf(port);
return (portAsInt >= startOfRange && portAsInt <= endOfRange);
}
}