Computer >> 컴퓨터 >  >> 프로그램 작성 >> C++

C++에서 IP 주소 확인

<시간/>

이 기사는 C++ 코드 프로그래밍을 통해 올바른 IP(인터넷 프로토콜) 주소를 검증하는 데 목적을 두고 있습니다. IP 주소는 32비트 점 십진 표기법으로 0에서 255 사이의 4개의 10진수 세그먼트로 나뉩니다. 또한 이 숫자는 연속적으로 점으로 구분됩니다. IP 주소는 네트워크에서 호스트 시스템을 고유한 방식으로 식별하여 이들 간의 연결을 설정하는 목적을 제공합니다.

따라서 사용자 측에서 입력한 올바른 IP 주소를 검증하기 위해 다음 알고리즘은 다음과 같이 올바른 IP 주소를 식별하기 위해 코드 시퀀스가 ​​정확히 구체화되는 방법을 간략하게 설명합니다.

알고리즘

START
   Step-1: Input the IP address
   Step-2: Spilt the IP into four segments and store in an array
   Step-3: Check whether it numeric or not using
   Step-4: Traverse the array list using foreach loop
   Step-5: Check its range (below 256) and data format
   Step-6: Call the validate method in the Main()
END

따라서 다음 알고리즘에 따라 IP 주소의 유효성을 검사하기 위해 작성된 다음 C++에서 숫자 형식, 범위 및 입력 데이터 분할을 각각 결정하기 위해 몇 가지 필수 기능이 사용됩니다.

#include <iostream>
#include <vector>
#include <string>
using namespace std;
// check if the given string is a numeric string or not
bool chkNumber(const string& str){
   return !str.empty() &&
   (str.find_first_not_of("[0123456789]") == std::string::npos);
}
// Function to split string str using given delimiter
vector<string> split(const string& str, char delim){
   auto i = 0;
   vector<string> list;
   auto pos = str.find(delim);
   while (pos != string::npos){
      list.push_back(str.substr(i, pos - i));
      i = ++pos;
      pos = str.find(delim, pos);
   }
   list.push_back(str.substr(i, str.length()));
   return list;
}
// Function to validate an IP address
bool validateIP(string ip){
   // split the string into tokens
   vector<string> slist = split(ip, '.');
   // if token size is not equal to four
   if (slist.size() != 4)
      return false;
   for (string str : slist){
      // check that string is number, positive, and range
      if (!chkNumber(str) || stoi(str) < 0 || stoi(str) > 255)
         return false;
   }
   return true;
}
   // Validate an IP address in C++
int main(){
   cout<<"Enter the IP Address::";
   string ip;
   cin>>ip;
   if (validateIP(ip))
      cout <<endl<< "***It is a Valid IP Address***";
   else
      cout <<endl<< "***Invalid IP Address***";
   return 0;
}

표준 C++ 편집기를 사용하여 위 코드를 컴파일한 후 다음과 같이 입력 번호 10.10.10.2가 올바른 IP 주소인지 여부를 정식으로 확인하는 다음과 같은 출력이 생성됩니다.

출력

Enter the IP Address:: 10.10.10.2
***It is a Valid IP Assress***