ipv4數字轉換
阿新 • • 發佈:2018-11-05
#Ipv4轉換為十進位制數
def ipv42dec(ipv4):
if checkipv4(ipv4):
splits = ipv4.split(".")
result=0
if len(splits)==4:
for i in range(4):
result+= int(splits[i])*(256**(3-i))
return str(result)
else:
return ""
else:
return ""
#校驗Ipv4的格式
def checkipv4(ipv4):
matchobj = re.match(r'^(((\d{1,2})|(1\d{1,2})|(2[0-4]\d)|(25[0-5]))\.){3}((\d{1,2})|(1\d{1,2})|(2[0-4]\d)|(25[0-5]))$',ipv4)
if matchobj:
return True
else:
return False
#將十進位制數轉換為ipv4
def dec2ipv4(dec):
if checkdec( dec) and int(dec)<=4294967295:
iplist=[]
num= int(dec)
for i in range(3):
num,modnum=divmod(num,256)
iplist.insert(0,str(modnum))
iplist.insert(0,str(num))
return '.'.join(iplist)
else:
return ""
#校驗十進位制數字
def checkdec(dec) :
matchobj = re.match(r'(0[dD])?[0-9]+$',dec)
if matchobj:
return True
else:
return False
測試用例
class IPv4MethodsTest(unittest.TestCase):
def test_ipv42dec(self):
self.assertEqual(IPNumConvertMethods.ipv42dec('192.69.199.28'),'3225798428')
self.assertEqual(IPNumConvertMethods.ipv42dec('0.0.0.0'), '0')
self.assertEqual(IPNumConvertMethods.ipv42dec('255.255.255.255'), '4294967295')
self.assertEqual(IPNumConvertMethods.ipv42dec('255.255.255'), '')
self.assertEqual(IPNumConvertMethods.ipv42dec('255.255.255.256'), '')
class DecMethodsTest(unittest.TestCase):
def test_dec2ipv4(self):
self.assertEqual(IPNumConvertMethods.dec2ipv4('10'),'0.0.0.10')