判断IP是否在IP段内

项目当中衍生出来的一道题,给定一个IP段以及一个IP,判断这个IP是否在此IP段内。IP段的表示方法有两种,一种如192.168.1.0/24,另一种如192.168.1.1-254
例:

1.
input:  192.168.1.0/24
        192.168.1.56
output: true
//192.168.1.0/24表示的IP范围是192.168.1.1~192.168.1.254192.168.1.5.6在此范围内,返回true
2.
input:  192.168.1.0-254
        192.168.1.56
output: true
//192.168.1.0-254表示的IP范围是192.168.1.1~192.168.1.254192.168.1.5.6在此范围内,返回true       

C实现方法

#include<stdio.h>
#include<string.h>
#include<stdbool.h>
#include<stdlib.h>
typedef unsigned int uint32_t;
typedef unsigned char u_char;
uint32_t ngx_convert_ip_to_uint(char* base) ;
bool ngx_is_black_ip_style_two(char* base, char* src);
bool ngx_is_black_ip_style_one(char* base, char* src);
int main()
{
    char        s[30], r[30], *pos;
    bool        ans;

    scanf("%s\n%s", (char*)&s, (char*)&r);
    pos = strchr(s, '/');
    if (pos) {
         ans = ngx_is_black_ip_style_one(s, r);
    } else {
         ans = ngx_is_black_ip_style_two(s, r);
    }
    printf("ans = %d\n", ans);
    return 0;
}

//192.168.1.1-254
bool ngx_is_black_ip_style_two(char* base, char* src)
{
    int          num = 0;
    char        *pos;
    uint32_t     res[3] = {0,0,0};

    pos = strchr(base, '-');
    *pos = '\0';
    //IP 下限
    res[0] = ngx_convert_ip_to_uint(base);
    num = atoi(pos+1);
    printf("num = %d\n", num);  
    //IP上限 
    res[1] = res[0] + num;
    //待匹配IP
    res[2] = ngx_convert_ip_to_uint(src);
    printf("res = %u\t%u\t%u\n", res[0], res[1], res[2]);
    if (res[2] > res[0] && res[2] < res[1])
        return true;
    return false;

}

//Ip 192.168.0.1/24
bool ngx_is_black_ip_style_one(char* base, char* src)
{
    int          num = 0;
    char        *pos;
    uint32_t     res[3] = {0,0,0};

    pos = strchr(base, '/');
    *pos = '\0';
    //IP 下限
    res[0] = ngx_convert_ip_to_uint(base);
    num = atoi(pos+1);
    printf("num = %d\n", num);  
    //IP上限 
    res[1] = res[0] + (1 << (32 - num));
    //待匹配IP
    res[2] = ngx_convert_ip_to_uint(src);
    printf("res = %u\t%u\t%u\n", res[0], res[1], res[2]);
    if (res[2] > res[0] && res[2] < res[1])
        return true;
    return false;

}

//IP 转换成数字
uint32_t ngx_convert_ip_to_uint(char* base) 
{
    char       *pos, *index;
    uint32_t    res = 0;    

    index = pos = base;
    while (*pos) {
        if (*pos == '.') {
            *pos = '\0';
            res = (res << 8) + atoi(index);
            printf("res = %u\n",res);
            index = pos+1;
        }
        pos++;
    }
    res = (res << 8) + atoi(index); 
    return res;
}
全部评论

相关推荐

点赞 评论 收藏
分享
04-10 11:37
黑河学院 运营
点赞 评论 收藏
分享
1jian10:48h没写面评会变成这样
点赞 评论 收藏
分享
03-29 17:05
门头沟学院 Java
asdasdasda...:我前段时间找工作焦虑,有几天连续熬夜熬穿了,然后心脏突然不舒服,立马躺床上睡觉了,然后第二天还是不舒服,去看医生说是心率不齐,吓得我后面天天早早睡觉,调养身体,过了好几天才好过来。所以真的,工作这些东西哪有那么重要,最多钱多一点钱少一点,降低物欲。活着才是最重要的,现在想想真的后怕
如何排解工作中的焦虑
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务