Python判斷內網IP

def ip_into_int(ip):
# 先把 192.168.1.13 變成16進制的 c0.a8.01.0d ,再去了「.」後轉成10進制的 3232235789 便可。
# (((((192 * 256) + 168) * 256) + 1) * 256) + 13
return reduce(lambda x,y:(x<<8)+y,map(int,ip.split('.')))python

def is_internal_ip(ip):
    ip = ip_into_int(ip)
    net_a = ip_into_int('10.255.255.255') >> 24
    net_b = ip_into_int('172.31.255.255') >> 20
    net_c = ip_into_int('192.168.255.255') >> 16
    return ip >> 24 == net_a or ip >>20 == net_b or ip >> 16 == net_c

if __name__ == '__main__':
    ip = '192.168.0.1'
    print ip, is_internal_ip(ip)
    ip = '10.2.0.1'
    print ip, is_internal_ip(ip)
    ip = '172.16.1.1'
    print ip, is_internal_ip(ip)

結果:code

[root@ns_10.2.1.242 test]$ python p.py 
192.168.0.1 True
10.2.0.1 True
172.16.1.1 True

map和reduce用法:ip

>>> map(int, '12.34'.split('.'))
[12, 34]
>>> reduce(lambda x,y:(x<<8)+y, [12, 34])
3106
# 左移8位,至關於乘以256
>>> 12 * 256 + 34
3106
相關文章
相關標籤/搜索