Method for python3 to Judge IP Address
- 2021-09-16 07:17:14
- OfStack
In this paper, we share the specific code of python3 to judge IP address for your reference. The specific contents are as follows
Input a string of characters, judge whether the string is a dot-point decimal IP address, if it is converted to hexadecimal output, otherwise output "Error"
Note: The input may be any one string, such as "abc. bas. fefe. 4r4" or "23.23. 11.23. 123"
These are all illegal IP addresses
For example
Input: 192.41. 6.20
Output: 0xC0290614
Input: 257.32. 23.1
Output: Error
Solution 1
import re
def isIP(str):
p = re.compile('^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$')
if p.match(str):
return True
# else:
# return False
myStr = input()
if isIP(myStr):
print(IP(myStr).strHex().upper())
# ip = list(map(int, myStr.split('.')))
# print('0x', end='')
# for i in ip:
# print(hex(i)[2:].upper().rjust(2, '0'), end='')
else:
print('Error')
Solution 2:
def change(lis):
if len(lis)!=4:
return 'Error'
try: # Determine whether the string has non-numbers
lis=[int(i) for i in lis]
except:
return 'Error'
for i in lis:
if i<0 or i>255: # Judge ip Is the address legal
return 'Error'
temp='0x' # Record 16 Binary number
for i in lis:
a=hex(int(i))[2:].upper().rjust(2,'0') # Convert to 16 Binary system
# if len(a)!=2:
# a='0'+a
temp+=a
return temp
s=list(map(str,input().split('.')))
print(change(s))
Solution 3
l = input().split(".")
if len(l) != 4:
print("Error")
else:
s = ""
for i in l:
try:
num = int(i)
if num > 255 or num < 0:
print("Error")
s = ""
break
else:
s += hex(num)[2:].upper().rjust(2, "0")
except ValueError:
print("Error")
s = ""
break
if s:
print("0x" + s)