免责声明:网站内容仅供个人学习记录,禁做商业用途,转载请注明出处。

版权所有 © 2017-2020 NEUSNCP个人学习笔记 辽ICP备17017855号-2

python处理IP地址和子网掩码

hxy    2019年8月26日 19:15:09

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





 
最近更新: 2019年12月29日 12:04:33
浏览: 3.0K

[[total]] 条评论

添加评论
  1. [[item.time]]
    [[item.user.username]] [[item.floor]]楼
  2. 点击加载更多……
  3. 添加评论