python处理IP地址和子网掩码

hxy    2019-08-26 19:15

1. 根据 ip + 子网压掩码 获取 ip 地址的范围:
from IPy import IP as IP
ip = IP('220.218.1.0/24')
print(ip[0])
print(ip[-1])
print(len(ip))
2. ip地址转为long数字地址
def ip_to_long(ip_addr):
    '''
    @description: 将IP地址转化为long 数字地址
    @param : 
    @return: 
    '''    
    ips = ip_addr.split('.')
    return int(ips[0]) * 256 * 256 * 256 + int(ips[1]) * 256 * 256 + int(ips[2]) * 256 + int(ips[3])
  3. ip 地址 + 子网掩码获取所在网段
from IPy import IP
input_IP = '220.218.1.122'
list1 = input_IP.split('.')
if len(list1) != 4:
  exit()

for i in list1:
  if i.isdigit() == True and int(i) >=0 and int(i) <= 255:
    pass
  else:
    exit()

input_Netmask = '255.255.255.0'
list2 = input_Netmask.split('.')
if len(list2) != 4:
  exit()

for i in list2:
  if i.isdigit() == True and int(i) >=0 and int(i) <= 255:
    pass
  else:
    exit()

print ("您所在的网段为:%s" % (IP(input_IP).make_net(input_Netmask)))

参考资料:
  1. https://pypi.org/project/IPy/
  2. https://www.jb51.net/article/70325.htm
  3. https://www.cnblogs.com/kaixiang/p/7131187.html





 
Last Modified: 2019-12-29 12:04
Views: 2.9K

[[total]] comments

Post your comment
  1. [[item.time]]
    [[item.user.username]] [[item.floor]]Floor
  2. Click to load more...
  3. Post your comment