You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用C++实现带掩码的IPv4子网地址合法性校验?

校验带掩码的IPv4子网地址的C++实现

要搞定这个校验功能,核心思路就是把输入字符串拆成IPv4地址段和前缀掩码段,分别验证合法性,具体步骤如下:

1. 拆分输入字符串

首先得确保输入里有且只有一个/,还要避开//32、20.0.0.0/这种首尾带/的破格式。用C++标准库的string::find和substr就能搞定:

  • 找不到/、/在开头或结尾,直接判非法;
  • 要是找到多个/,也直接返回false。

2. 校验IPv4地址段

就用你提到的inet_pton函数,注意这几点:

  • 地址族指定AF_INET;
  • inet_pton返回1才表示地址格式合法,返回0是格式错,-1是地址族无效;
  • 得保证地址段不是空字符串,避免inet_pton处理空串出问题。

3. 校验前缀掩码段

掩码必须是0到32之间的整数,要做两步检查:

  • 先确认掩码段全是数字,不能有字母、符号之类的;
  • 转成整数后,必须在0 ≤ mask ≤32范围内,还要处理转整数失败的情况(比如掩码是超大数或非数字)。

完整代码示例

#include <string>
#include <cstring>
#include <arpa/inet.h> // 引入inet_pton
#include <cctype>
#include <stdexcept>

bool isValidIPv4Subnet(const std::string& subnet) {
    // 查找分隔符/的位置
    size_t slashPos = subnet.find('/');
    // 检查/的合法性:不能没有、不能在开头或结尾
    if (slashPos == std::string::npos || slashPos == 0 || slashPos == subnet.size() - 1) {
        return false;
    }
    // 检查是否存在多个/
    if (subnet.find('/', slashPos + 1) != std::string::npos) {
        return false;
    }

    std::string ipPart = subnet.substr(0, slashPos);
    std::string maskPart = subnet.substr(slashPos + 1);

    // 校验IPv4地址
    struct in_addr addr;
    if (inet_pton(AF_INET, ipPart.c_str(), &addr) != 1) {
        return false;
    }

    // 校验掩码:先检查是否全为数字
    for (char c : maskPart) {
        if (!std::isdigit(c)) {
            return false;
        }
    }
    // 转换为整数并检查范围
    try {
        int mask = std::stoi(maskPart);
        if (mask < 0 || mask > 32) {
            return false;
        }
    } catch (const std::invalid_argument&) {
        // 非数字字符串转换失败
        return false;
    } catch (const std::out_of_range&) {
        // 数字超出int范围(比如超长数字串)
        return false;
    }

    return true;
}

哪些情况会被拦截?

  • 格式错误:20.0.0.0//32(多个/)、/32(空地址)、20.0.0.0/(空掩码);
  • 非法IPv4:256.0.0.0/24、20.0.0.a/24、20.0.0.0.1/24;
  • 非法掩码:20.0.0.0/-1(负数)、20.0.0.0/33(超过32)、20.0.0.0/abc(非数字)。

内容的提问来源于stack exchange,提问作者brokendreams

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 14:52:53