android 根据ip计算netmask,c实现 ip、掩码 计算网段

#define BYTE_LEN 8

#define BYTE_NUM 4

#define NET_SEGMENT_SIZE 64

int strtok_str(uint8_t * p[], int max_p_num, uint8_t * str, const uint8_t * spl) {     int in = 0;     uint8_t *buf = str;     uint8_t *outer_ptr = NULL;     uint8_t *inner_ptr = NULL;     while ((p[in] = strtok_r(buf, spl, (char **) &outer_ptr)) != NULL)     {         buf = p[in];         if (in >= max_p_num)         {             break;         }         while ((p[in] = strtok_r(buf, spl, (char **) &inner_ptr)) != NULL)         {             in++;             buf = NULL;         }         buf = NULL;     }     return in; } static int get_effective_bit(unsigned long num, int *effective_bits) {     int r;     int i;     for (i = 0; i < BYTE_LEN; i++)     {         r = num % 2;         num = num / 2;         if (r == 1)         {             *effective_bits += 1;         }     }     return 0; } int get_net_segment(uint8_t * net_segment, uint8_t * ip_str,                     uint8_t * netmask_str) {     int i;     int num;     uint8_t *ip_list[BYTE_NUM];     uint8_t *netmask_list[BYTE_NUM];     int effective_bits = 0;     for (i = 0; i < BYTE_NUM; i++)     {         ip_list[i] = NULL;         netmask_list[i] = NULL;     }     if (strtok_str(ip_list, BYTE_NUM, ip_str, ".") !=         (num = strtok_str(netmask_list, BYTE_NUM, netmask_str, ".")))     {         ELOG_ERR("strtok_str error in get_net_segment\n");         return -1;     }     if (num != BYTE_NUM)     {         ELOG_ERR("error in get_net_segment\n");         return -1;     }     for (i = 0; i < num; i++)     {         if (netmask_list[i] == NULL || ip_list[i] == NULL)         {             ELOG_ERR                 ("netmask_list[i] == NULL || ip_list[i]==NULL in get_net_segment\n");             return -1;         }         get_effective_bit(atoi(netmask_list[i]), &effective_bits);         if (i != num - 1)         {             snprintf(net_segment + strlen(net_segment),                      NET_SEGMENT_SIZE, "%d.",                      atoi(ip_list[i]) & atoi(netmask_list[i]));         }         else         {             snprintf(net_segment + strlen(net_segment),                      NET_SEGMENT_SIZE, "%d/%d",                      atoi(ip_list[i]) & atoi(netmask_list[i]), effective_bits);         }     }     ELOG_INFO("net_segment==========%s\n", net_segment);     return 0; }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值