IP Address Validation

  • + 0 comments

    Solution for JAVA with explanation:

    Scanner scan = new Scanner(System.in); int n =scan.nextInt(); scan.nextLine();

    String input = "";
    
        Pattern ipv4 = Pattern.compile("(([0]?[0-9]?[0-9]|[1][0-9][0-9]|[2][0-5][0-5])(\\.)){3}([0]?[0-9]?[0-9]|[1][0-9][0-9]|[2][0-5][0-5])");
    
        Pattern ipv6 = Pattern.compile("([a-f\\d]{1,4}(:){1}){7}[a-f\\d]{1,4}");
    Matcher m;
    
    for(int i=0;i<n;i++){
        input = scan.nextLine();
        m = ipv4.matcher(input);
        if(m.matches()){
            System.out.println("IPv4");
        }
        else {
            m = ipv6.matcher(input);
            if(m.matches()){
                System.out.println("IPv6");
            }
            else {
                System.out.println("Neither");
            }
        }
        input = "";
    }
    
    scan.close();