问题描述
在Java 6中确定给定地址是否为有效网络掩码的最简单方法是什么?我找到了一种解决方案,该解决方案基本上创建了一个有效IP数组以供比较(例如"255.255.255.255","255.255.255.254","255.255.255.252"等).有没有更简单的方法,或者这是最好的方法?
What is the easiest way in Java 6 to determine whether a given address is a valid net mask? I have found one solution which basically creates an array of valid IPs to use in a comparison (i.e. "255.255.255.255", "255.255.255.254", "255.255.255.252", etc...). Is there an easier way or is this the best way?
推荐答案
如果您很乐意包含一个外部依赖项,那么Apache的 commons.net 可能会满足您的需求.
If you're happy to include an external dependency, then Apache's commons.net may have what you're looking for.
看看 SubnetUtils 及其 SubnetInfo 嵌套班级.您可以使用IP地址和掩码构造SubnetUtils
. 构造函数会引发异常,并且 SubnetInfo.html#isInRange 可以告诉您IP是否在掩码的范围内.
Have a look at SubnetUtils and its SubnetInfo nested class. You can construct a SubnetUtils
with an IP address and a mask. The constructor throws an exception if your mask is invalid, and SubnetInfo.html#isInRange can tell you if an IP is in a mask's range.
这篇关于确定网络掩码在Java中是否有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!