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 地址由四个十进制数构成。在实际生产环境中,还需要对输入进行更严格的验证和错误处理。

相关推荐
我不是懒洋洋几秒前
【数据结构】二叉树链式结构的实现(二叉树的遍历、使用二叉树的基本方法、二叉树的创建和销毁)
c语言·数据结构·c++·经验分享·算法·链表·visual studio
玖別ԅ(¯﹃¯ԅ)5 分钟前
C++ Qt + OpenCV 实现本地人脸识别系统:摄像头采集、ONNX模型加载、人脸库比对完整流程
c++·qt
iwS2o90XT6 分钟前
Kotlin标准库:实用函数
android·开发语言·kotlin
csbysj20207 分钟前
C# 命名空间(Namespace)
开发语言
永远睡不够的入11 分钟前
C++11新特性(3):lambda不是玄学:从编译器生成的仿函数类彻底搞懂 C++ 匿名函数
开发语言·c++
SilentSamsara11 分钟前
综合实战:用 Python 做一个待办事项管理器(CLI 版)
开发语言·python·青少年编程·pycharm
HAPPY酷13 分钟前
UE5 C++ 避坑指南:暴力移除 Electronic Nodes 插件,回归纯净开发
开发语言·c++·ue5
huipeng92613 分钟前
分布式服务部署详解
java·开发语言·spring cloud·微服务
eqwaak014 分钟前
4 月技术快讯|Rust 1.90 正式发布,系统级开发再进化
开发语言·后端·rust
小此方14 分钟前
Re:思考·重建·记录 现代C++ C++11篇 (四)C++ Lambda 全解析:编译器是如何为你生成仿函数的?
开发语言·c++·c++11·现代c++