• Python实现网络和IP地址计算


    import math
    def bin_to_ip(bin_str):
        if len(bin_str) < 32:
            bin_str ='%s%s'%('0' * (32 - len(bin_str)), bin_str)
        a = bin_str[0:8]
        b = bin_str[8:16]
        c = bin_str[16:24]
        d = bin_str[24:32]
        return '%s.%s.%s.%s' % (str(int('0b%s' % a, 2)), str(int('0b%s' % b, 2)), str(int('0b%s' % c, 2)), str(int('0b%s' % d, 2)))
    
    # 二进制并计算
    def bin_and(bin_str, mask_str):
        new_str = ''
        for i in range(32):
            if mask_str[i] == '1' and bin_str[i] == '1':
                new_str = "%s%s"%(new_str, 1)
            else:
                new_str = "%s%s"%(new_str, 0)
        return new_str
    # 十进制转换成二进制字符
    def str_to_bin(ip, mask):
        ip_bin_str = ''
        for s in str(ip).split('.'):
            b_str = ''
            for i in range(8):
                try:
                    b_str = '%s%s' % (b_str, (bin(int(s))[2:][i]))
                except:
                    b_str = '%s%s' % ('0', b_str)
            ip_bin_str = '%s%s' % (ip_bin_str, b_str)
        mask_bin_str = '1' * int(mask)
        if len(mask_bin_str) < 32:
            mask_bin_str = mask_bin_str + '0' * (32 - int(mask))
        return ip_bin_str, mask_bin_str
    def main(ip_mask):
        ip_str, mask_str = ip_mask.split('/')
        ip_bin_str, mask_bin_str = str_to_bin(ip_str, mask_str)
        host_ip_bin = (bin_and(ip_bin_str, mask_bin_str))
        ip_num = (int(math.pow(2, 32 - int(mask_str)))) - 2
        mask = bin_to_ip(mask_bin_str)
        host_ip = bin_to_ip(host_ip_bin)
        ip_list = []
        for i in range(ip_num+2):
            ip_list.append(bin_to_ip(str(bin(int('0b%s' % host_ip_bin, 2) + i))[2:]))
        first_use_ip = ip_list[1]
        last_use_ip = ip_list[-2]
        broad_ip = ip_list[-1]
        use_ips = ip_list[1:-1]
        return ip_num, mask, host_ip, first_use_ip, last_use_ip, broad_ip, use_ips
    if __name__ == '__main__':
        ip_mask = '192.168.32.125/29'
        ip_num, mask, host_ip, first_use_ip, last_use_ip, broad_ip, use_ips = main(ip_mask)
    
        print('-+-'*8)
        print('ip num:', ip_num)
        print('mask', mask)
        print('host ip:', host_ip)
        print('first use ip:', first_use_ip)
        print('last use ip:', last_use_ip)
        print('broad ip:', broad_ip)
  • 相关阅读:
    磁盘上没有足够的空间完成此操作的解决办法_Windows小知识
    使用XAMPP和DVWA在Windows7上搭建渗透测试环境
    使用WampServer和DVWA在Windows10上搭建渗透测试环境
    DOS系统常用命令
    Kali Linux图形界面与命令行界面的切换
    SQLMap入门之在Windows上安装SQLMap
    在Windows下同时安装Python2.x和Python3.x
    Python基础之Windows下Python3.x环境搭建
    在Linux上使用PGP签名验证文件完整性
    Ubuntu软件中心的完全启用
  • 原文地址:https://www.cnblogs.com/qingkongwuyun/p/15606182.html
Copyright © 2020-2023  润新知