目录
一、任务目标
1、判断用户输入IP的合法性,例如是否不符合IP地址的正确格式;
2、判断用户输入IP与本机IP是否在同一网段;
3、使用C++和QT实现;
二、判断用户输入IP的合法性
cpp
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
bool isValidIPAddress(const std::string& ipAddress) {
std::vector<int> ipSegments;
std::istringstream iss(ipAddress);
std::string segment;
while (std::getline(iss, segment, '.')) {
try {
int value = std::stoi(segment);
if (value < 0 || value > 255) {
return false;
}
ipSegments.push_back(value);
} catch (const std::exception& e) {
return false;
}
}
return ipSegments.size() == 4;
}
int main() {
std::string text = "192.168.1.3:502";
size_t delimiterPos = text.find(':');
std::string ipAddress = delimiterPos != std::string::npos ? text.substr(0, delimiterPos) : text;
if (isValidIPAddress(ipAddress)) {
std::cout << "The IP address is valid." << std::endl;
} else {
std::cout << "The IP address is invalid." << std::endl;
}
return 0;
}
三、判断用户输入IP与本机IP是否在同一网段
cpp
//使用Visual Studio
//项目属性->"Qt Project Settings"->"Qt Modules"->勾选"network"
#include <QtNetwork/QNetworkInterface>
#include <QtNetwork/QNetworkAddressEntry>
#include <QtNetwork/QAbstractSocket>
//获取本机IP
QHostAssress hostIP()
{
auto list = QNetworkInterface::allInterfaces();
foreach(QNetworkInterface interface,list)
{
//1、首先判断是不是以太网,过滤Wifi
if(interface.type() != QNetworkInterface::Ethernet)
continue;
//2、如果有安装虚拟机VMware,会出现虚拟网卡,需要过滤
if(interface.humanReadableName().contains("VMware"))
continue;
//3、一般会有两个IP地址,一ipv4一个ipv6,过滤ipv6
foreach(auto entry,interface.addressEntries())
{
if(entry.ip().protocol() == QAbstractSocket::IPv4Protocol)
return entry.ip();
}
}
return QHostAddress();
}
int main()
{
//获取本机IP
QHostAddress LocalIP = hostIP();
QString ipAddress = LocalIP.toString();
std::string text = ipAddress.toStdString();
//获取本机网段值
int extractedInt = -1;
std::string delimiter = ".";
std::vector<std::string> tokens;
std::string token;
std::istringstream tokenStream(text);
while (std::getline(tokenStream, token, '.')) {
tokens.push_back(token);
}
if (tokens.size() >= 3) {
std::string extracted = tokens[2];
extractedInt = std::stoi(extracted);
}
//获取用户输入IP的网段值
std::string InputIP = "192.168.1.3:502";
int extractedInt2 = -2;
std::vector<std::string> tokens2;
std::string token2;
std::istringstream tokenStream2(InputIP);
while (std::getline(tokenStream2, token2, '.')) {
tokens2.push_back(token2);
}
if (tokens2.size() >= 3) {
std::string extracted2 = tokens2[2];
extractedInt2 = std::stoi(extracted2);
}
//判断用户输入的IP是否与本机IP在同一网段
if(extractedInt == extractedInt2)
{
std::cout<<"在同一网段"<<std::endl;
}
else
{
std::cout<<"不在同一网段"<<std::endl;
}
return 0;
}
上述两项功能可以结合在一起使用,在"判断用户输入IP的合法性"后"判断用户输入IP与本机IP是否在同一网段"。
上述功能因笔者使用场景为QT的交互界面所以用到了QT的QtNetwork模块。
//上述代码为笔者在网页编写,如有错误望及时提出,感谢!