判断两个 IP 地址是否在同一个局域网中

文章目录

目的

如何判断两个 IP 地址是否在同一个局域网中, 核心知识点是出于一个网络号, 主要是通过本身ip 与 所处的子网掩码进行 & 计算处理是否处于同一个局域网中(在 TCP/IP协议规则里面,IP地址与子网掩码做与运算)。

代码实现

#include <iostream>
#include <bitset>
#include <string>

bool checkSameSubnet(const std::string& ip1, const std::string& ip2, const std::string& subnetMask) {
    // 将 IP 地址和子网掩码转换为无符号整数
    unsigned long ip1Value = std::bitset<32>(ip1).to_ulong();
    unsigned long ip2Value = std::bitset<32>(ip2).to_ulong();
    unsigned long subnetMaskValue = std::bitset<32>(subnetMask).to_ulong();

    // 逻辑与运算,获取网络部分
    unsigned long subnet1 = ip1Value & subnetMaskValue;
    unsigned long subnet2 = ip2Value & subnetMaskValue;

    // 比较网络部分是否相同
    return subnet1 == subnet2;
}

int main() {
    std::string ip1 = "192.168.1.100";
    std::string ip2 = "192.168.1.200";
    std::string subnetMask = "255.255.255.0";

    bool sameSubnet = checkSameSubnet(ip1, ip2, subnetMask);
    if (sameSubnet) {
        std::cout << "IP addresses are in the same subnet." << std::endl;
    } else {
        std::cout << "IP addresses are not in the same subnet." << std::endl;
    }

    return 0;
}
``
  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

道阻且长,行则降至

无聊,打赏求刺激而已

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值