Java中如何判断一个IP是否在一个网段里面?


=Start=

缘由:

功能开发需要,学习Java需要(之前有写过Python版本的,因为Python本身的特性以及netaddr模块,所以写起来很简单),后来发现Java里也有相关成熟的jar包,所以,也很简单。。。

正文:

参考解答:

# SubnetUtils
http://commons.apache.org/proper/commons-net/javadocs/api-3.6/index.html

# IpAddressMatcher
https://docs.spring.io/spring-security/site/docs/4.2.4.RELEASE/apidocs/org/springframework/security/web/util/matcher/IpAddressMatcher.html

# pom.xml
<dependency>
	<groupId>org.springframework.security</groupId>
	<artifactId>spring-security-web</artifactId>
	<version>4.2.3.RELEASE</version>
</dependency>

# test.java
import org.springframework.security.web.util.matcher.IpAddressMatcher;

private boolean matches(String ip, String subnet) {
    IpAddressMatcher ipAddressMatcher = new IpAddressMatcher(subnet);
    return ipAddressMatcher.matches(ip);
}

&

public class IpCheckMatching {
    /**
     * check if IP address match pattern
     *
     * @param pattern
     *            *.*.*.* , 192.168.1.0-255 , *
     * @param address
     *            - 192.168.1.1<BR>
     *            <code>address = 10.2.88.12  pattern = *.*.*.*   result: true<BR>
     *                address = 10.2.88.12  pattern = *   result: true<BR>
     *                address = 10.2.88.12  pattern = 10.2.88.12-13   result: true<BR>
     *                address = 10.2.88.12  pattern = 10.2.88.13-125   result: false<BR></code>
     * @return true if address match pattern
     */
    public static boolean checkIPMatching(String pattern, String address)
    {
        if (pattern.equals("*.*.*.*") || pattern.equals("*"))
            return true;

        String[] mask = pattern.split("\\.");
        String[] ip_address = address.split("\\.");
        for (int i = 0; i < mask.length; i++)
        {
            if (mask[i].equals("*") || mask[i].equals(ip_address[i]))
                continue;
            else if (mask[i].contains("-"))
            {
                int min = Integer.parseInt(mask[i].split("-")[0]);
                int max = Integer.parseInt(mask[i].split("-")[1]);
                // if (max > 255) max = 255;
                int ip = Integer.parseInt(ip_address[i]);
                if (ip < min || ip > max)
                    return false;
            }
            else
                return false;
        }
        return true;
    }

    public static void main(String[] args) {
        String ipPattern = "*,*.*.*.*,10.2.88.12,10.2.88.12-13,10.2.88.5-125,10.2.88.13-256"; //byte类型最大值(127)
        String ipStr = "10.2.88.12";
        for (String ip: ipPattern.split(",")) {
            System.out.print(ipStr + " in " + ip + " ?\t");
            System.out.println(checkIPMatching(ip, ipStr));
        }
    }
}

 

参考链接:

=END=


《 “Java中如何判断一个IP是否在一个网段里面?” 》 有 2 条评论

  1. 如何用Java进行有效的IP地址校验?
    java judge string is ip address
    https://stackoverflow.com/questions/4581877/validating-ipv4-string-in-java
    http://docs.guava-libraries.googlecode.com/git-history/v10.0.1/javadoc/com/google/common/net/InetAddresses.html
    `
    // 推荐Google Guava的这个
    import com.google.common.net.InetAddresses;
    boolean isValid = InetAddresses.isInetAddress(“1.2.3.4”);
    `

    Validate IPv4 address in Java
    https://stackoverflow.com/Questions/5667371/validate-ipv4-address-in-java
    `
    private static final Pattern PATTERN = Pattern.compile(
    “^(([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d\\d?|2[0-4]\\d|25[0-5])$”);

    public static boolean validate(final String ip) {
    return PATTERN.matcher(ip).matches();
    }
    `

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注