I need to determine if given IP address is from some special network in order to authenticate automatically.
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
Option 1:
Use
spring-security-web
's IpAddressMatcher. Unlike Apache Commons Net, it supports both ipv4 and ipv6.Option 2 (a lightweight solution!):
The code in previous part works perfectly fine but it needs
spring-security-web
to be included.If you are not willing to include Spring framework in your project, you may use this class which is a slightly modified version of the original class from Spring, so that it has no non-JDK dependencies.
NOTICE: Notice that for using this option, it's your responsibility to carefully examine the license to make sure by using this code, you are not in violation of any terms mandated by the aforementioned license. (Of course publishing this code to Stackoverflow.com by me is not a violation.)
I know this is very old question, but I stumbled upon this when I was looking to solve the same problem.
There is commons-ip-math library that I believe does a very good job. Please note that as of May 2019, there hasn't been any updates to the library (Could be that its already very mature library). Its available on maven-central
It supports working with both IPv4 and IPv6 addresses. Their brief documentation has examples on how you can check if an address is in a specific range for IPv4 and IPv6
Example for IPv4 range checking:
To check An IP in a subnet, I used isInRange method in SubnetUtils class. But this method have a bug that if your subnet was X, every IP address that lower than X, isInRange return true. For example if your subnet was 10.10.30.0/24 and you want to check 10.10.20.5, this method return true. To deal with this bug I used below code.
You can also try
or shorter
The open-source IPAddress Java library will do this in a polymorphic manner for both IPv4 and IPv6 and handles subnets. Disclaimer: I am the project manager of that library.
Example code:
Output:
here is an Version that works with IPv4 and IPv6 one with Prefix and one with Network Mask.