在 C++ 中驗證 IP 地址


本文旨在利用 C++ 程式碼程式設計驗證正確的 IP(網際網路協議)地址。IP 地址是一種 32 位點分十進位制表示法,分為四個十進位制數字段,範圍從 0 到 255。此外,這些數字由點順序分隔。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

因此,根據演算法,起草以下 c++ 驗證 IP 地址,其中採用了幾個必需函式來確定數字形式、範圍以及分別拆分輸入資料;

示例

 線上演示

#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***

更新於: 29-11-2019

2K+ 瀏覽

開啟 職業生涯

透過完成課程獲得認證

立即開始
廣告
© . All rights reserved.