十六进制格式化IP地址范围搜索

时间:2014-10-25 11:52:47

标签: c ip-address binary-search-tree

我正在使用一个文本文件,其中有两列是ipaddress的起始范围,例如ipaddress的columnB结束范围,

1002000 1003fff
1011000 1011fff
1012000 1013fff
1021000 1021fff
1022000 1023fff
1024000 1027fff
1030000 103ffff
1041000 1041fff
1042000 1043fff
1044000 1047fff
1080000 108ffff

我的searchkey ipaddress假设为1021234所以我想为此实现二进制搜索我已经将它们存储在数组中,如inbuf [a]和inbuf [a + 1]。如何检查4个文件,例如abc.txt xyz .txt sww.txt找到落在这些文件中的ipaddress并返回文件名。

1 个答案:

答案 0 :(得分:-1)

#include <stdio.h>
#include <stdlib.h>

typedef struct range {
    unsigned start;
    unsigned end;
} Range;

#define MAX_N 256

Range table[MAX_N];

#define range_file "ip_range.txt"
int load_table(void){
    int n = 0;
    unsigned start, end;
    FILE *fp = fopen(range_file, "r");

    if(!fp){
        fprintf(stderr, "%s can't open.", range_file);
        exit(EXIT_FAILURE);
    }
    while(2==fscanf(fp, "%x %x", &start, &end)){
        table[n].start = start;
        table[n++].end = end;
    }
    fclose(fp);
    return n;
}

int cmp_range(int no, unsigned key){
    if(key < table[no].start)
        return -1;
    else if(key > table[no].end)
        return 1;
    return 0;
}

int search(unsigned key, int low, int high){
    while(low <= high){
        int mid = (low + high)/2;
        int status = cmp_range(mid, key);
        if(status == 0)
            return mid;//find
        else if(status < 0)
            high = mid -1;
        else
            low = mid + 1;
    }
    return -1;//not find
}

int main (void){
    int n = load_table();
    unsigned key = 0x1021234;
    int i = search(key, 0, n-1);

    if(i < 0)
        printf("%x not found in range table.\n", key);
    else {
        printf("%x in ", key);
        printf("%x-%x\n", table[i].start, table[i].end);
    }

    return 0;
}