判断两个ip地址是否在同一子网内

该程序使用C++实现,通过将IP地址转换为整数数组并应用子网掩码来判断两个IP地址是否属于同一子网。主要功能包括:将IP地址字符串转化为整数数组,比较两个IP地址在应用子网掩码后的前缀是否相同,从而确定它们是否在同一子网内。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
#include <cstring>
#include <cstdlib>

using namespace std;

bool Addr_to_Array(char* addr, int* array)
{
    bool ret = (addr != NULL );
    char* sub = NULL;
    int i = 0;
    
    if( ret)
    {
        sub = strtok(addr,"."); // 分割字符串
        
        while(sub != NULL)
        {
            array[i] = atoi(sub); // 字符串变为整数
            i++;
            sub = strtok(NULL,"."); 
         } 
         
     } 
     
     return ret;

}

int checkNetSegment(char* mask_addr, char* ip1_addr, char* ip2_addr)
{
    bool  ret = true;
    
    int add[4] = {0};
    int p1[4] = {0};
    int p2[4] = {0};
    
    ret = ret && Addr_to_Array(mask_addr, add);
    ret = ret && Addr_to_Array(ip1_addr, p1);
    ret = ret && Addr_to_Array(ip2_addr, p2);
    
    if(ret)
    {
        for(int i=0; i<4; i++)
        {
            if( (p1[i] & add[i]) == (p2[i] & add[i]) )
            {            
                if( i == 3)
                {
                    //cout << "ip1 and ip2 are in the same netsegment." << endl;
                }
                    continue;
            }
            else
            {
                //cout << "ip1 and ip2 are not in the same netsegment." << endl;
                ret = false;
                break;
            }
        }
    }
    
    return  ret;           //static_cast<int>(ret);
        
}

int main()
{
    char mask_addr[] = "255.255.255.0";
    char ip1_addr[] = "192.168.1.120";
    char ip2_addr[] = "192.168.1.128";
    
    int ret = checkNetSegment(mask_addr, ip1_addr, ip2_addr);
    
    if( 1 == ret ) 
    {
        cout << "ip1 and ip2 are in the same netsegment." << endl; 
    }
    else
    {
        cout << "ip1 and ip2 are not in the same netsegment." << endl;
    }

    return 0;
}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值