Determine if net mask is valid in Java

岁酱吖の 提交于 2019-12-07 16:06:57

问题


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?


回答1:


If you're happy to include an external dependency, then Apache's commons.net may have what you're looking for.

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.




回答2:


What about this pseudocode:

function IS_VALID(MASK)
  boolean zeroStart = false
  for each byte in MASK
    for each bit
      if bit = 1 and zeroStart = false
        continue
      if bit = 1 and zeroStart = true
        return INVALID_MASK
      if bit = 0 and zeroStart = false
        zeroStart = true
      if bit = 0 and zeroStart = true
        continue
  return VALID_MASK



回答3:


I think Serg10's answer is the simplest.

If you need to avoid external dependencies, then you should use Inet4Address to convert the IP address String into an array of bytes, and then analyse the bytes. Trying to analyse the String using a regex or by comparing with a fixed set of strings is liable to give the wrong answer:

  • The components of an IP address can have leading zeros.
  • An IP address can also be written with three, two or even just one component.

Refer to the Inet4Address javadoc for a description of what an IP address string can look like.




回答4:


You could try using a regular expression

Pattern p = Pattern.compile("^((2[0-5][0-5]|1[\\d][\\d]|[\\d][\\d]|[\\d])\\.){3}(2[0-5][0-5]|1[\\d][\\d]|[\\d][\\d]|[\\d])$");
String ip = "255.255.255.0.2";
Matcher m = p.matcher(ip);
if(m.matches()) {
    //valid
}


来源:https://stackoverflow.com/questions/10090720/determine-if-net-mask-is-valid-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!