C++判定终端ip和目标ip是否在同一局域网内

程序如下:用于判断给定的终端 IP、子网掩码和目标 IP 是否在同一局域网内。请注意,这个程序假设 IP 地址是用整数表示的。

cpp 复制代码
#include <iostream>
#include <sstream>
#include <vector>
#include <bitset>

// Function to check if two IPs are in the same network
bool checkSameNetwork(std::string terminalIP, std::string subnetMask, std::string targetIP) {
    // Split the IP strings into octets
    std::istringstream terminalStream(terminalIP), subnetStream(subnetMask), targetStream(targetIP);
    std::vector<int> terminalOctets, subnetOctets, targetOctets;
    std::string octet;

    while (std::getline(terminalStream, octet, '.')) {
        terminalOctets.push_back(std::stoi(octet));
    }

    while (std::getline(subnetStream, octet, '.')) {
        subnetOctets.push_back(std::stoi(octet));
    }

    while (std::getline(targetStream, octet, '.')) {
        targetOctets.push_back(std::stoi(octet));
    }

    // Perform bitwise AND operation on corresponding octets of IP and subnet mask
    for (size_t i = 0; i < 4; ++i) {
        if ((terminalOctets[i] & subnetOctets[i]) != (targetOctets[i] & subnetOctets[i])) {
            return false; // IPs are not in the same network
        }
    }

    return true; // IPs are in the same network
}

int main() {
    std::string terminalIP, subnetMask, targetIP;

    // Input terminal IP, subnet mask, and target IP
    std::cout << "Enter terminal IP: ";
    std::cin >> terminalIP;

    std::cout << "Enter subnet mask: ";
    std::cin >> subnetMask;

    std::cout << "Enter target IP: ";
    std::cin >> targetIP;

    // Check if terminal IP and target IP are in the same network
    bool sameNetwork = checkSameNetwork(terminalIP, subnetMask, targetIP);

    // Output the result
    if (sameNetwork) {
        std::cout << "true\n";
    } else {
        std::cout << "false\n";
    }

    return 0;
}

需要注意的是,此程序假定输入的 IP 地址是以点分十进制表示法给出的,并且子网掩码和 IP 地址都是有效的。此外,它假设 IPv4 地址,每个 IP 地址由四个十进制数构成。在实际生产环境中,还需要对输入进行更严格的验证和错误处理。

相关推荐
卷无止境5 分钟前
SFML 深度解读:一个教科书级 C++ 多媒体库的内功心法
c++·后端
hai31524754324 分钟前
九章编译法:DEEPSEEK V3.2汇编编译实例
java·开发语言
lkshop24 分钟前
Next.js 网站 SEO 优化:从 SSR、Sitemap 到结构化数据
开发语言·javascript·ecmascript
灯澜忆梦1 小时前
GO_函数_2
开发语言·golang·xcode
apihz1 小时前
经纬度制作高清卫星图片免费 API 接口详解
开发语言·ios·swift
娇气的红酒2 小时前
微软对PHP支持的改进,及其它一些胡言乱语
开发语言·microsoft·php
霸道流氓气质2 小时前
Harness Engineering 模块化指令实战:告别 600 行巨型 AGENTS.md
开发语言·人工智能·python
盐焗鹌鹑蛋2 小时前
【C++】set和map
c++
j7~2 小时前
【算法】专题二:滑动窗口之水果成蓝,找到字符串中所有字⺟异位词等算法题
c++·算法·滑动窗口·水果成蓝·最小字串覆盖·优选算法精选
一拳一个呆瓜2 小时前
【STL】iostream 编程:文件输出流的成员函数
c++·stl