😎풀이

  1. queryIPIPv4 형식인지 확인
    1-1. 1~3자리 수가 .과 연결된 네 그룹으로 구성되어 있는가
    1-2. 각 ip가 숫자로 구성된 0~255 정수의 형태인가
  2. queryIPIPv6 형식인지 확인
    2-1. 16을 의미하는 f까지 0~f 까지의 문자로 구성된 8개의 그룹인지 확인
  3. 두 형식 모두 아닌 경우, Neither 반환
function validIPAddress(queryIP: string): string {
    if(isValidIPv4(queryIP)) return 'IPv4'
    if(isValidIPv6(queryIP)) return 'IPv6'
    return 'Neither'
};

function isValidIPv4(str: string) {
    if(!str.match(/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/g)) return false
    const splitted = str.split(".").filter(Boolean)
    if(splitted.length !== 4) return false
    for(const ip of splitted) {
        if(ip.length > 1 && ip.startsWith('0')) return false
        if(ip.match(/[^\d]/g)) return false
        const numIP = Number(ip)
        if(numIP < 0 || numIP > 255) return false
    }
    return true
}

function isValidIPv6(str: string) {
    const splitted = str.split(':')
    if(splitted.length !== 8) return false
    for(const ip of splitted) {
        if(ip.length < 1 || ip.length > 4) return false
        if(ip.match(/[^\d\w]/g)) return false
        const lowercase = ip.toLowerCase()
        for(const char of lowercase) {
            if(char > 'f') return false
        }
    }
    return true
}
profile
내 지식을 공유할 수 있는 대담함

0개의 댓글