判断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;
}
全部评论

相关推荐

牛客339922477号:都不用reverse,直接-1。一行。啥送分题
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务