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

相关推荐
charlie1145141913 分钟前
深入理解Qt的SetWindowsFlags函数
开发语言·c++·qt·原理分析
呜喵王阿尔萨斯10 分钟前
编程中的英语
c语言·c++
likeGhee1 小时前
python缓存装饰器实现方案
开发语言·python·缓存
whoarethenext1 小时前
使用 C++/Faiss 加速海量 MFCC 特征的相似性搜索
开发语言·c++·faiss
项目題供诗1 小时前
黑马python(二十五)
开发语言·python
慌糖1 小时前
RabbitMQ:消息队列的轻量级王者
开发语言·javascript·ecmascript
醇醛酸醚酮酯2 小时前
Qt项目锻炼——TODO清单(二)
开发语言·数据库·qt
jioulongzi2 小时前
记录一次莫名奇妙的跨域502(badgateway)错误
开发语言·python
向阳@向远方2 小时前
第二章 简单程序设计
开发语言·c++·算法
Mr_Xuhhh3 小时前
信号与槽的总结
java·开发语言·数据库·c++·qt·系统架构