zoukankan      html  css  js  c++  java
  • python 判断两个ip是不是处于同一网段


    a_ip:10.10.15.100
    b_ip:10.10.15.101
    c_ip:10.10.10.100
    netmask:255.255.255.0

    def numtobinary(num):
    binary = ''
    a = int(num)
    while 1:
        if a == 0 or a == 1:
        binary = '%s%s' % (str(a), binary)
        break
            num = a % 2
    binary = '%s%s' % (str(num), binary)
    a = a / 2
    binarylen = len(binary)
    binary = '%s%s' % ('0' * (8 - binarylen), binary)
    return binary

    上面这个函数,是将一个 0<=x<=255的十进制数转换成二进制数。

    def yu_num(ip, netmask):
    ips = ip.split('.')
    ipstr = numtobinary(ips[0]) + numtobinary(ips[1]) + numtobinary(ips[2]) + numtobinary(ips[3])
    netmasks = netmask.split('.')
    netmaskstr = numtobinary(netmasks[0]) + numtobinary(netmasks[1]) + numtobinary(netmasks[2]) + numtobinary(netmasks[3])
    ipandnetmasknum = ''
    for i in xrange(32):
    if ipstr[i] == netmaskstr[i]:
    ipandnetmasknum += ipstr[i]
    else:
    ipandnetmasknum += '0'
    return ipandnetmasknum
    上面这个函数, 是获取一个ip和netmask的与的运算

    a_num = yu_num(a_ip, netmask) #a_num : '00001010000010100000111100000000'

    b_num = yu_num(b_ip, netmask) #b_num : '00001010000010100000111100000000'
    c_num = yu_num(c_ip, netmask)     #c_num : '00001010000010100000101000000000'

    if a_num == b_num:
      pass
      #是处于同一个网段
    else:
      pass
      #不处于同一个网段
  • 相关阅读:
    简洁的Python
    python docker
    django-rest-framework笔记-类视图篇
    itertools库
    python 内置库
    python 数据分类
    python元组
    django-rest-framework笔记-请求与响应篇
    Centos 安装.NET CORE 3.1
    api接口签名验证
  • 原文地址:https://www.cnblogs.com/wozuilang-mdzz/p/9579255.html
Copyright © 2011-2022 走看看