python 对ip段处理

需求:  ip段 20.20.20.20-20.21.11.11 插入数据库

-------------------------------------------------------

写下来供以后重用或有需要的同行~

#生成下一次循环的边界条件
def get_side(pos,now):
    global begin,end
    global first,last

    #   find_side                   #
    #---------in---------------
    #begin 110.67.1.95 end 111.67.1.95
    #first 110.x.x.x   last 111.x.x.x
    #pos 110 now 0
    #---------out--------------
    #first 110.67.x.x  last 111.255.x.x
    #                               #
    find_side = lambda begin, end, pos, fisrt, last, now:\
                ( pos == first[now] and begin[now + 1] or 1, pos == last[now] and end[now + 1] or 255)

    first[now + 1],last[now + 1] = find_side(begin,end,pos,first,last,now)
    return range(first[now + 1],last[now + 1] + 1)


def gen_ip(ip):
    '''
    in in 110.67.1.30-110.67.1.32
    out '{"110.67.1.30", "110.67.1.31", "110.67.1.33"}'
    '''
    #ip段范围
    global begin, end
    #临时列表,存储边界条件
    global first, last
    sides = ip.split('-')
    begin = map(lambda x:int(x),sides[0].split('.'))
    end   = map(lambda x:int(x),sides[1].split('.'))

    first[0] = begin[0]
    last[0] = end[0]
    ip_str = "'{%s}'"
    tmp = ""

    for pos_one in range(begin[0],end[0] + 1):
        for pos_two in get_side(pos_one,0):
            for pos_three in get_side(pos_two,1):
                for pos_four in get_side(pos_three,2):
                    str = '"%d.%d.%d.%d",' % (pos_one, pos_two, pos_three, pos_four)
                    tmp += str

    return ip_str % tmp.rstrip(',')

思路为从ip起始段的首位开始循环,共4层循环。 

整个转换需要注意的问题只有一个, 如何在循环内正确的处理边界值。

例如 10.10.10.10-10.10.20.1

在第三个字段应该分别进行如下循环:  10.10 - 10.255; 11.1 -11.255 .... 19.255;  20.1

考虑一下,这里其实分为三种情况,当前循环的是起始、过渡和终止字段。

因此#14 行做了两个三元操作,大致类似于  pos == from ? begin+1 : 1, pos == to ? end + 1 :255

实现了根据当前循环内容与起始段、终止段是否一致,写入对应的边界

当然,在特殊情况下1. ip前两段不同,后两段一致时 会导致缺少部分数据,不过因为这次我在项目里用到的IP范围不可能达到后面这个范围,因此忽略了这个bug。

posted @ 2012-09-04 14:04  阿毛小猪  阅读(6462)  评论(8编辑  收藏  举报