匹配指定的ip属于哪个地址段

类别:软件工程 点击:0 评论:0 推荐:

匹配指定的ip属于哪个地址段

作者:梅劲松
程序提供:hoxide

因为写DNS服务器,来根据客户端的访问,返回指定ip地址.所以需要用到匹配ip属于哪个地址段的功能.hoxide帮忙用python实现了出来,在这里表示感谢.代码如下 :
注意:hoxide注明本程序为MIT 授权.

class NetPool:
    def __init__(self):
        self.Pool = dict()
        self.Pool['net'] = '0.0.0.0'
       
    def add(self, ip):
        a = map(int, ip.split('.'))
        p = self.Pool
        for i in range(len(a)-1, -1, -1):
            if a[i] != 0 :
                k = i+1
                break
        for i in range(k):
            ia = a[i]
            try:
                p = p[ia]
            except:
                p[ia] = dict()
                p = p[ia]
        p['net'] = ip
    def get(self, ip):
        a = map(int, ip.split('.'))
        p = self.Pool
        st = list()
        for ia in a:
            try:
                if ia == 0:
                    st.append(p)
                p = p[ia]
            except:
                break
        st.append(p)
        while st:
            p = st.pop()
            try:
                return p['net']
            except:
                pass
        return 'no such net'

def test():
    import pprint
    pp = pprint.PrettyPrinter()
    P = NetPool()
    Net = [
        '11.1.1.0',
        '12.3.2.0',
        '11.1.2.0',
        '12.0.0.0',
        '11.0.1.0',
        '11.0.0.0'
        ]
    IP = [
        '11.1.1.2',
        '12.3.2.5',
        '11.1.2.2',
        '12.5.7.8',
        '11.0.1.9',
        '11.253.9.1',
        '254.254.255.255'
        ]
    #print 'NET'
    for ip in Net:
        print 'NET: ', ip
        P.add(ip)
    for ip in Net:
        print 'NET: ', ip
        P.add(ip)
    pp.pprint(P.Pool)
    for ip in IP:
        print ip, ' in ', P.get(ip)
       
if __name__ == '__main__':
    test()

本文地址:http://com.8s8s.com/it/it32565.htm