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;
}

猜你喜欢

转载自blog.csdn.net/a_tu_/article/details/78978997
今日推荐