C++判断ip是否有效,是否是内网网段,计算网段

#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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值