check Ip Mask - Java Network

Java examples for Network:IP Address

Description

check Ip Mask

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        String ip = "java2s.com";
        System.out.println(checkIpMask(ip));
    }//from  w ww . j  a v  a2s. c  om

    public static String checkIpMask(String ip) {
        String ipParts[] = ip.split("\\.");
        if (ipParts.length != 4)
            return "IP address must have 4 parts";
        String message = checkIpMaskPart(ipParts[0]);
        if (message != null)
            return message;
        message = checkIpMaskPart(ipParts[1]);
        if (message != null)
            return message;
        message = checkIpMaskPart(ipParts[2]);
        if (message != null)
            return message;
        message = checkIpMaskPart(ipParts[3]);
        if (message != null)
            return message;
        else
            return null;
    }

    private static String checkIpMaskPart(String part) {
        int dash;
        if ("*".equals(part))
            return null;
        dash = part.indexOf('-');
        if (dash == -1) {
            int value = Integer.parseInt(part);
            if (value < 0 || value > 255)
                return (new StringBuilder())
                        .append("Value out of range in '").append(part)
                        .append("'").toString();
            //break MISSING_BLOCK_LABEL_219;
        }
        int from;
        from = Integer.parseInt(part.substring(0, dash));
        if (from < 0 || from > 255)
            return (new StringBuilder())
                    .append("'From' value out of range in '").append(part)
                    .append("'").toString();
        int to;
        try {
            to = Integer.parseInt(part.substring(dash + 1));
            if (to < 0 || to > 255)
                return (new StringBuilder())
                        .append("'To' value out of range in '")
                        .append(part).append("'").toString();
        } catch (NumberFormatException e) {
            return (new StringBuilder())
                    .append("Integer parsing error in '").append(part)
                    .append("'").toString();
        }
        if (from > to)
            return (new StringBuilder())
                    .append("'From' value is greater than 'To' value in '")
                    .append(part).append("'").toString();
        return null;
    }
}

Related Tutorials