'자바 IP주소 입력 체크'에 해당되는 글 1건

728x90

How to alidate IP address with regular expression


IP 주소와 Subnet Mask 입력이 잘못된 것인지 체크하는 메소드를 작성해봤다.


import java.util.regex.Pattern;

public class Validation {

    public static void main(String[] args) {
       
        String inputValue = "10.10.10.256/21";
        String result = IPSubnetMask(inputValue);
        if(result.equals("1")){
            System.out.println("IP 주소와 서브넷 마스크를 정상적으로 입력했습니다.");
        } else if(result.equals("2")){
            System.out.println("ip 주소 입력이 잘못되었습니다.");
        } else if(result.equals("3")){
            System.out.println("서브넷 마스크가 맞나요?");
        } else {
            System.out.println("IP 주소와 서브넷 마스크 입력 정보를 확인하세요.");
        }       

    }
   
    private static String IPSubnetMask(String masArray){
        if(masArray.contains("/")){
            String[] input_ipsubnet = masArray.split("/"); // / 기호로 분리하라.
            String ipaddress = input_ipsubnet[0];
            String subnetMask = input_ipsubnet[1];
            System.out.println("ipaddress :" + ipaddress + ", subnetMask : " + subnetMask);
            if(IP_Validation.matcher(ipaddress).matches()) {
                if(Integer.parseInt(subnetMask)< 23) {
                    return "3"; // 서브넷 마스크 확인 필요
                } else {
                    return "1"; // 정상
                }               
            } else {
                return "2"; // IP주소 입력 체크
            }
        } else {
            return "0";
        }
    }
   
    private static final Pattern IP_Validation =
            Pattern.compile("^((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9])\\.){0,3}"+
                    "((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9])){0,1}$");
   
}
 





'안드로이드 > Java 문법' 카테고리의 다른 글

Java 추상 클래스  (0) 2019.08.19
[Java] 다형성  (0) 2019.06.30
자바 클래스 개념 이해 예제  (0) 2019.05.27
자바 Arraylist  (0) 2019.05.26
Java BubbleSort  (0) 2019.05.13
블로그 이미지

Link2Me

,