IP段去重

原文

下面的代码是从网上拷贝的,经过了一番学习研究后觉得写的比较好,就挂上来,也留作以后工作所用

这段代码的思想也是先排序,然后去重的

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

typedef struct node 
{
    unsigned int start;
    unsigned int end;
} Node;

void print_out(unsigned int start_pos, unsigned int end_pos)
{
    printf("%u.%u.%u.%u ", start_pos >> 24,
                          start_pos >> 16 & 0xFF,
                          start_pos >> 8 & 0xFF,
                          start_pos & 0xFF);
    printf("%u.%u.%u.%u\n", end_pos >> 24,
                          end_pos >> 16 & 0xFF,
                          end_pos >> 8 & 0xFF,
                          end_pos & 0xFF);
    return;
}

static int
cmpNodep(const void *p1, const void *p2)
{
    if (((Node *)p1)->start > ((Node *)p2)->start)
        return 1;
    if (((Node *)p1)->start < ((Node *)p2)->start)
        return -1;
    return (((Node *)p1)->end - ((Node *)p2)->end);
}

int main()
{
    unsigned int start_pos, end_pos;
    unsigned int i, tmp;
    int start[4], end[4];
    Node node_array[3000];
    int node_array_size;

    node_array_size = 0;
    while (1)
    {
        if (scanf("%u.%u.%u.%u %u.%u.%u.%u", &start[0], &start[1], &start[2], &start[3], 
                                            &end[0], &end[1], &end[2], &end[3]) <= 0)
            break;
        start_pos = start[0]*256*256*256 + start[1]*256*256 + start[2]*256 + start[3];
        end_pos = end[0]*256*256*256 + end[1]*256*256 + end[2]*256 + end[3];
        node_array[node_array_size].start = start_pos;
        node_array[node_array_size].end = end_pos;
        node_array_size++;
    }
    qsort(node_array, node_array_size, sizeof(Node), cmpNodep);

    start_pos = node_array[0].start; 
    end_pos = node_array[0].end; 
    for (i=1; i<node_array_size; i++)
    {
        // If next start before current end (+1 for merge),
	// update the new end if necessary
        if (node_array[i].start <= end_pos + 1) 
        {
            if (node_array[i].end > end_pos) 
                end_pos = node_array[i].end;
        }
        else 
        {
	    // If next start after current end, 
	    // print this section and start new one
            print_out(start_pos, end_pos);
            start_pos = node_array[i].start; 
            end_pos = node_array[i].end;
        }
    }
    print_out(start_pos, end_pos);
        
    return 0;
}

输入:

1.1.1.1 2.2.2.2
3.3.3.3 4.4.4.4
1.1.1.1 2.2.2.9
3.3.3.8 4.4.4.9
sdf

结果:
1.1.1.1 2.2.2.9
3.3.3.3 4.4.4.9

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值