Skip to content

Instantly share code, notes, and snippets.

@diuis
Last active February 27, 2020 13:25
Show Gist options
  • Save diuis/373c6630a115ed0a514679efecf4b41a to your computer and use it in GitHub Desktop.
Save diuis/373c6630a115ed0a514679efecf4b41a to your computer and use it in GitHub Desktop.
ip range validation
import static org.assertj.core.api.Assertions.assertThat;
import java.math.BigInteger;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Optional;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
public class TestIpAddress {
public TestIpAddress() {
}
@ParameterizedTest
@CsvSource({ "[10.10.10.0..10.10.10.255],10.10.10.9,true", "[10.10.10.0..10.10.10.255],10.10.11.0,false" })
void testIpRange(String ipRange, String ip, boolean expected) throws UnknownHostException {
var optionalRange = Optional.ofNullable(ipRange)
.filter(range -> range.startsWith("["))
.filter(range -> range.endsWith("]"))
.map(range -> range.subSequence(1, range.length() - 1)
.toString())
.map(range -> range.split("\\.\\."))
.filter(values -> values.length == 2);
var addressMin = new BigInteger(InetAddress.getByName(optionalRange.get()[0])
.getAddress()).longValue();
var addressMax = new BigInteger(InetAddress.getByName(optionalRange.get()[1])
.getAddress()).longValue();
var addressBetween = new BigInteger(InetAddress.getByName(ip)
.getAddress()).longValue();
var actual = Math.max(addressMin, addressBetween) == Math.min(addressBetween, addressMax);
assertThat(actual).isEqualTo(expected);
}
@ParameterizedTest
@CsvSource({ "[10.10.10.0..10.10.10.255],10.10.10.9,true", "[10.10.10.0..10.10.10.255],10.10.11.0,false" })
void testIpRangePredicate(String ipRange, String ip, boolean expected) {
Predicate<String> predicate = ipToValidate -> {
return Optional.ofNullable(ipRange)
.filter(range -> range.startsWith("[") && range.endsWith("]"))
.map(range -> range.subSequence(1, range.length() - 1)
.toString())
.map(rangeWithoutBraces -> rangeWithoutBraces.split("\\.\\."))
.filter(values -> values.length == 2)
.map(rangeArray -> {
try {
var addressMin = new BigInteger(InetAddress.getByName(rangeArray[0])
.getAddress()).longValue();
var addressMax = new BigInteger(InetAddress.getByName(rangeArray[1])
.getAddress()).longValue();
var addressToValidate = new BigInteger(InetAddress.getByName(ipToValidate)
.getAddress()).longValue();
return Math.max(addressMin, addressToValidate) == Math.min(addressToValidate, addressMax);
} catch (UnknownHostException e) {
return false;
}
})
.orElse(false);
};
var actual = predicate.test(ip);
assertThat(actual).isEqualTo(expected);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment