Last active
April 1, 2017 17:01
-
-
Save tiberiosantos/c393feb69dcd31c637e466994ccb59c7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
try: | |
input = raw_input | |
range = xrange | |
except NameError: | |
pass | |
class IPv4: | |
def __init__(self, address): | |
octets = map(int, address.split('.')) | |
octets = tuple(filter(lambda o: o in range(0, 256), octets)) | |
if len(octets) != 4: | |
raise ValueError('Invalid address!') | |
self.octets = octets | |
def value(self, *octets): | |
return '.'.join(map(str, *octets)) | |
def bin(self): | |
return self.value([bin(o).split('0b')[1].zfill(8) | |
for o in self.octets]) | |
def __and__(self, other): | |
a = map(lambda x: x[0] & x[1], zip(self.octets, other.octets)) | |
return IPv4(self.value(tuple(a))) | |
def __or__(self, other): | |
o = map(lambda x: x[0] | x[1], zip(self.octets, other.octets)) | |
return IPv4(self.value(tuple(o))) | |
def __invert__(self): | |
i = map(lambda x: ~x & 0xff, self.octets) | |
return IPv4(self.value(tuple(i))) | |
def __str__(self): | |
return self.value(self.octets) | |
def __repr__(self): | |
return '<IPV4 ({})>'.format(self.__str__()) | |
show = ''' | |
ip: {0} | |
{1} | |
------------------------------------------------ | |
mask: {2} | |
{3} | |
------------------------------------------------ | |
network: {4} | |
{5} | |
------------------------------------------------ | |
broadcast: {6} | |
{7} | |
''' | |
if __name__ == '__main__': | |
ip = IPv4(input('IP: ')) | |
mask = IPv4(input('Mask: ')) | |
network = ip & mask | |
broadcast = ~mask | network | |
print(show.format(ip, ip.bin(), mask, mask.bin(), network, network.bin(), | |
broadcast, broadcast.bin())) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment