简体   繁体   中英

Determine if two ip addresses are the same network python

Alright so I need to take two inputted ip addresses that are inputed like 128.233.17.12 and then a given subnet mask and be able to output if they are on the same network.
I managed to get them into binary and formatted right, but I don't know how to compare them now. In order to determine if they are on the same network I need to do vertical addition. IE

#128.233.17.12 = 10000000111010010001000|100001100
#128.233.12.17 = 10000000111010010000110|000010001
#255.255.0.0   = 11111111111111110000000000000000

The top two ip's need to be the same only when the subnet (bottom) has a 1. Therefore these are on the same network. This is my code thus far but I'm not sure how to input all the variables.

IPAdress1 = input("Please enter a dotted quad notation IP address: ")
IPAdress2 = input("Please enter another: ")
SubnetMask = input("Please enter the subnet mask: ")

binaryIP1 = [bin(int(IPAdress1))[2:].rjust(8,'0') for IPAdress1 in IPAdress1.split('.')]
IP1 = ''.join(binaryIP1)

binaryIP2 = [bin(int(IPAdress2))[2:].rjust(8,'0') for IPAdress2 in IPAdress2.split('.')]
IP2 = ''.join(binaryIP2)

binarysub = [bin(int(SubnetMask))[2:].rjust(8,'0') for SubnetMask in SubnetMask.split('.')]
sub = ''.join(binarysub)
i=0
j=0

for (i,j) in zip(binaryIP1,binaryIP2):
    if i == j:
        print("Same Network" )
    else:
        print("Different networks")

anyone help is appreciated

I recommend netaddr module to play with addresses:

from netaddr import IPNetwork

if IPNetwork("128.233.17.12/255.255.0.0") == IPNetwork("128.233.12.17/255.255.0.0"):
    print "Same!"
else:
    print "Different!"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM