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

相关推荐
LaoZhangGong123几秒前
W5500使用ioLibrary库创建TCP客户端
网络·经验分享·stm32·网络协议·tcp/ip
tyatyatya1 分钟前
MATLAB 神经网络的系统案例介绍
开发语言·神经网络·matlab
hweiyu0012 分钟前
C#学习教程(附电子书资料)
开发语言·学习·c#
q5673152314 分钟前
图片爬虫通过模板及使用说明
开发语言·爬虫·tcp/ip·golang
superior tigre19 分钟前
C++学习:六个月从基础到就业——C++11/14:列表初始化
c++·学习
正在走向自律25 分钟前
Conda 完全指南:从环境管理到工具集成
开发语言·python·conda·numpy·fastapi·pip·开发工具
啊吧怪不啊吧31 分钟前
C/C++之内存管理
开发语言·汇编·c++
北极象33 分钟前
Go语言处理HTTP下载中EOFFailed
开发语言·http·golang
superior tigre36 分钟前
C++学习:六个月从基础到就业——C++11/14:decltype关键字
c++·学习
技术流浪者39 分钟前
C/C++实践(十)C语言冒泡排序深度解析:发展历史、技术方法与应用场景
c语言·数据结构·c++·算法·排序算法