I am trying to store IP ranges in Java. Can't find a particular data structure to store IP ranges. If the IP range is between 19.0.0.0 to 19.0.0.255, I need a way to check whether IP 19.0.0.1 is in the range. Which is the suitable data structure for it?
Asked
Active
Viewed 50 times
0
-
2Put the four bytes into a long (not int because it's signed), then just compare. Or `&` and compare if you're using masks. – tgdavies Jul 05 '22 at 04:58
-
A string would work with a regex check, see here to get you started [Validate if input string is a number between 0-255 using regex](https://stackoverflow.com/questions/31684083/validate-if-input-string-is-a-number-between-0-255-using-regex) or a quick search for "java regex validate ip address" should take you to a member of tutorials/examples – sorifiend Jul 05 '22 at 05:03
-
Does this answer your question: [Java IP Validator](https://stackoverflow.com/questions/19709657/java-ip-validator) – sorifiend Jul 05 '22 at 05:08
-
see this answer https://stackoverflow.com/a/12057933/2310289 – Scary Wombat Jul 05 '22 at 05:15
-
Sorry this question was closed. The short answer is to convert IP addresses into longs, and then, since each CIDR range corresponds to a contiguous range, put the addresses at which validity changes into a TreeMap. Lookup an IP using TreeMap.floorEntry() – Matt Timmermans Jul 05 '22 at 13:11