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
#不处于同一个网段