Method Check whether IP address is legal. - Java java.lang

Java examples for java.lang:Assert

Description

Method Check whether IP address is legal.

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        String IPString = "java2s.com";
        System.out.println(checkIP(IPString));
    }//from www.j a v a  2 s.  c o  m

    /**
     *
     * Method Check  whether IP address is legal.
     *
     * @param IPString The value to be checked.
     *
     */
    public static boolean checkIP(String IPString) {
        if (IPString != null && IPString.length() == 12) {
            int ip = Integer.parseInt(IPString.substring(0, 3));
            if (ip < 1 || ip >= 224 || ip == 127)
                return false;
            ip = Integer.parseInt(IPString.substring(3, 6));
            if (ip < 0 || ip > 255)
                return false;
            ip = Integer.parseInt(IPString.substring(6, 9));
            if (ip < 0 || ip > 255)
                return false;
            ip = Integer.parseInt(IPString.substring(9, 12));
            if (ip < 1 || ip > 254)
                return false;

            return true;
        } else
            return false;
    }
}

Related Tutorials