Programing/C++

IPv4 주소를 확인하는 C++ 정규식 코드

Ezzi 2023. 5. 4. 16:46
반응형

 

이 함수는 문자열로 표현된 IPv4 주소를 인자로 받아, 해당 주소가 유효한지 여부를 확인합니다. 

 

만약 주소가 유효하다면 true를 반환하고, 그렇지 않으면 false를 반환합니다. 

 

이 함수를 사용하려면, std::regex 및 std::string 헤더를 포함시켜야 합니다.

 

#include <regex>
#include <string>

bool isValidIPAddress(const std::string& ipAddress) {
    std::regex ipv4_regex(
        R"((\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3}))");
    std::smatch match;
    if (std::regex_match(ipAddress, match, ipv4_regex)) {
        for (size_t i = 1; i < match.size(); ++i) {
            int octet = std::stoi(match[i]);
            if (octet < 0 || octet > 255) {
                return false;
            }
        }
        return true;
    }
    return false;
}

 

반응형