Loading

多网络计算方法详解

一、多网络计算方法详解

  有时候我们想比较两个网段是否存在包含、重叠等关系,比如同网络但不同prefixlen会认为是不相等的网段,如10.0.0.0/16不等于10.0.0.0/24,另外即使具有相同的prefixlen但处于不同的网络地址,同样也视为不相等,如10.0.0.0/16不等于192.0.0.0/16。IPy支持类似于数值型数据的比较,以帮助IP对象进行比较,如:

>>> IP('10.0.0.0/24') < IP('12.0.0.0/24')
True

判断IP地址和网段是否包含于另一个网段中,如下:

>>> '192.168.1.100' in IP('192.168.1.0/24')
True
>>> IP('192.168.1.0/24') in IP('192.168.0.0/16')
True

判断两个网段是否存在重叠,采用IPy提供的overlaps方法,如:

>>> IP('192.168.0.0/23').overlaps('192.168.1.0/24')
1                    #返回1代表存在重叠
>>> IP('192.168.1.0/24').overlaps('192.168.2.0')
0                    #返回0代表不存在重叠

示例:根据输入的IP或子网返回网络、掩码、广播、反向解析、子网数、IP类型等信息

#1/usr/bin.env python
from IPy import IP

#接收用户输入,参数为IP地址或网段地址
ip_s = input('Please input an IP or net-range: ')
ips = IP(ip_s)
if len(ips) > 1:                               #为一个网络地址
    print('net: %s' %ips.net())                #输出网络地址
    print('netmask: %s' %ips.netmask())        #输出网络掩码地址
    print('broadcast: %s' %ips.broadcast())    #输出网络广播地址
    print('reverse address: %s' %ips.broadcast())      #输出地址反向解析
    print('subnet: %s' %len(ips))                      #输出网络子网数
else:     #为单个IP地址
    print('reverse address: %s' %ips.reverseNames()[0])      #输出IP反向解析
print('hexadecimal: %s' %ips.strHex())            #输出十六进制地址
print('binary ip: %s' %ips.strBin())            #输出二进制地址
print('iptype: %s' %ips.iptype())            #输出地址类型,输出地址类型,如PRIVATE、PUBLIC、LOOPBACK等

分别输入网段、IP地址的运行返回结果如下:

[root@localhost test]# python simple1.py
Please input an IP or net-range: 192.168.1.0/24
net: 192.168.1.0
netmask: 255.255.255.0
broadcast: 192.168.1.255
reverse address: 192.168.1.255
subnet: 256
hexadecimal: 0xc0a80100
binary ip: 11000000101010000000000100000000
iptype: PRIVATE
[root@localhost test]# python simple1.py
Please input an IP or net-range: 192.168.1.20
reverse address: 20.1.168.192.in-addr.arpa.
hexadecimal: 0xc0a80114
binary ip: 11000000101010000000000100010100
iptype: PRIVATE

 

posted @ 2018-05-24 21:40  KubeSec  阅读(965)  评论(0编辑  收藏  举报