子网掩码转换:长度<-->点分10进制

来源:互联网 发布:sql insert into 错误 编辑:程序博客网 时间:2024/05/29 04:35
转自http://blog.chinaunix.net/uid-105044-id-2952041.html
子网掩码常见的表示方法有两种:
一种用长度表示, 比如24, 表示掩码中含有二进制1的个数
一种用点分10进制表示,比如255.255.255.0
 
以下是我写的一个二者之间相互转换的函数,请参考:
 

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>

/*
 * len --> *.*.*.*
 * 25 --> 255.255.255.128
 */

char* netmask_len2str(int mask_len, char* mask_str)
{
    int i;
    int i_mask;
    
    for (= 1, i_mask = 1; i < mask_len; i++)
    {
        i_mask = (i_mask << 1) | 1;
    }

    i_mask = htonl(i_mask << (32 - mask_len));
    strcpy(mask_str, inet_ntoa(*((struct in_addr *)&i_mask)));
    
    return mask_str;
}

/*
 * *.*.*.* --> len
 * 255.255.255.128 --> 25
 */

int netmask_str2len(char* mask)
{
    int netmask = 0;
    unsigned int mask_tmp;

    mask_tmp = ntohl((int)inet_addr(mask));
    while (mask_tmp & 0x80000000)
    {
        netmask++;
        mask_tmp = (mask_tmp << 1);
    }

    return netmask;    
}

int main(int argc, char** argv)
{
    int len = 0;
    char tmp[20] = {0};

    len = strlen(argv[1]);
    
    if (len > 2) 
        printf("%s --> %d\n", argv[1], netmask_str2len(argv[1]));
    else /* 1 ~ 32 */
        printf("%s --> %s\n", argv[1], netmask_len2str(atoi(argv[1]), tmp));
    
    return 0;
}

 

原创粉丝点击