IP位址格式判斷(IP address format​)

#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <algorithm>
#include <cctype>

// 检查一个字符串是否是有效的IPv4地址
bool isValidIPv4(const std::string& ip) {
    std::vector<std::string> segments;
    std::stringstream ss(ip);
    std::string segment;
    while (std::getline(ss, segment, '.')) {
        segments.push_back(segment);
    }
    if (segments.size() != 4) {
        return false;
    }
    for (const std::string& seg : segments) {
        if (seg.empty() || seg.size() > 3 || !std::all_of(seg.begin(), seg.end(), ::isdigit)) {
            return false;
        }
        if (seg[0] == '0' && seg.size() > 1) {
            return false;
        }
        int num = std::stoi(seg);
        if (num < 0 || num > 255) {
            return false;
        }
    }
    return true;
}

// 检查一个字符串是否是有效的IPv6地址
bool isValidIPv6(const std::string& ip) {
    std::vector<std::string> segments;
    std::stringstream ss(ip);
    std::string segment;
    while (std::getline(ss, segment, ':')) {
        segments.push_back(segment);
    }
    if (segments.size() != 8) {
        return false;
    }
    for (const std::string& seg : segments) {
        if (seg.empty() || seg.size() > 4) {
            return false;
        }
        for (char ch : seg) {
            if (!isxdigit(ch)) {
                return false;
            }
        }
    }
    // 检查是否有多余的冒号
    if (ip.back() == ':') {
        return false;
    }
    return true;
}

int main() {
    std::string ip;
    while (std::getline(std::cin, ip)) {
        if (isValidIPv4(ip)) {
            std::cout << "IPv4" << std::endl;
        } else if (isValidIPv6(ip)) {
            std::cout << "IPv6" << std::endl;
        } else {
            std::cout << "N" << std::endl;
        }
    }
    return 0;
}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值