#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <arpa/inet.h>
// 将IP地址字符串转换为32位整数表示
unsigned int ipToUint(const std::string &ipAddress)
{
unsigned int ip = 0;
std::istringstream iss(ipAddress);
std::string segment;
int shift = 24;
while (std::getline(iss, segment, '.'))
{
ip |= (std::stoi(segment) << shift);
shift -= 8;
}
return ip;
}
// 计算网段
unsigned int calculateNetworkSegment(unsigned int ip, unsigned int subnetMask)
{
return (ip & subnetMask);
}
// 将32位整数表示的IP地址转换为字符串形式
std::string uintToIp(unsigned int ip)
{
std::ostringstream oss;
oss << ((ip >> 24) & 0xFF) << '.'
<< ((ip >> 16) & 0xFF) << '.'
<< ((ip >> 8) & 0xFF) << '.'
<< (ip & 0xFF);
return oss.str();
}
// 检查 IP 是否在给定的 IP 段范围内
bool checkIpInRange(const std::string &ipAddress, const std::string &startIp, const std::string &endIp)
{
unsigned int ip = ipToUint(ipAddress);
unsigned int start = ipToUint(startIp);
unsigned int end = ipToUint(endIp);
return (ip >= start && ip <= end);
}
// 校验 IP 是否合法
bool isValidIP(const std::string &ipAddress)
{
struct sockaddr_in sa;
int result = inet_pton(AF_INET, ipAddress.c_str(), &(sa.sin_addr));
return result != 0;
}
// 校验 IP 是否为内网 IP
bool isPrivateIP(const std::string &ipAddress)
{
if (!isValidIP(ipAddress))
return false;
std::vector<std::pair<std::string, std::string>> privateIPRanges{
{"10.0.0.0", "10.255.255.255"},
{"172.16.0.0", "172.31.255.255"},
{"192.168.0.0", "192.168.255.255"}};
for (const auto &range : privateIPRanges)
{
if (checkIpInRange(ipAddress, range.first, range.second))
{
return true;
}
}
return false;
}
int main()
{
// 输入IP地址和子网掩码
std::string ipAddress = "192.168.1.100";
std::string subnetMask = "255.255.254.0";
// 将IP地址和子网掩码转换为32位整数表示
unsigned int ip = ipToUint(ipAddress);
unsigned int mask = ipToUint(subnetMask);
// 计算网段
unsigned int networkSegment = calculateNetworkSegment(ip, mask);
// 打印结果
std::cout << "IP地址: " << ipAddress << std::endl;
std::cout << "子网掩码: " << subnetMask << std::endl;
std::cout << "网段: " << uintToIp(networkSegment) << std::endl;
std::cout << "哈哈哈:" << isPrivateIP("乌漆嘛黑") << std::endl;
return 0;
}
C++判断ip是否有效,是否是内网网段,计算网段
于 2023-07-10 14:40:55 首次发布