Created
September 25, 2016 21:05
-
-
Save orymate/e5942dcdcd2393a3408de892a0bed3f3 to your computer and use it in GitHub Desktop.
IP4 and IP6 classes for use in SaltStack python state files (without netaddr)
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
class IP4(object): | |
""" | |
>>> print IP4("10.150.42.23") & IP4("255.255.0.0") | IP4("0.0.255.254") | |
10.150.255.254""" | |
def __init__(self, s="0.0.0.0"): | |
s = str(s) | |
self.ip = [int(i) for i in s.split(".")] | |
assert len(self.ip) == 4 | |
assert all(0 <= i <= 255 for i in self.ip) | |
def __and__(self, other): | |
result = self.__class__() | |
result.ip = [a & b for a, b in zip(self.ip, other.ip)] | |
return result | |
def __or__(self, other): | |
result = self.__class__() | |
result.ip = [a | b for a, b in zip(self.ip, other.ip)] | |
return result | |
def __str__(self): | |
return ".".join("%d" % i for i in self.ip) | |
class IP6(IP4): | |
""" | |
>>> print IP6("1:fefe::1:455:5:4") & IP6("ffff:ffff:ffff::") | IP6("::1234") | |
1:fefe:0:0:0:0:0:1234""" | |
def __init__(self, s="::"): | |
s = str(s) | |
if "::" in s: | |
left, right = (i.split(":") if i else [] for i in s.split("::", 1)) | |
zeros = ["0"] * (8 - len(left + right)) | |
strings = left + zeros + right | |
else: | |
strings = s.split(":") | |
self.ip = [int(i, 16) for i in strings] | |
assert len(self.ip) == 8 | |
assert all(0 <= i <= 0xffff for i in self.ip) | |
def __str__(self): | |
return ":".join("%x" % i for i in self.ip) | |
if __name__ == "__main__": | |
import doctest | |
doctest.testmod() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment