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;
}

 

반응형

'Programing > C++' 카테고리의 다른 글

c++ 파일 쓰기 예제코드  (0) 2023.03.11
C vs C++ 의 차이점  (0) 2023.02.27
C++ 커리큘럼 가이드  (0) 2023.02.26
STL Vector를 이용한 DataManger Class 만들기 예제  (0) 2012.05.30
Struct  (0) 2011.02.10