在 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***
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP