本文實(shí)例為大家分享了python3判斷IP地址的具體代碼,供大家參考,具體內(nèi)容如下
輸入一串字符,判斷該字符串是否為點(diǎn)分十進(jìn)制的IP地址,若是則轉(zhuǎn)換為16進(jìn)制輸出,否則輸出“Error”
注意:輸入可能是任意的一個(gè)字符串,比如“abc.bas.fefe.4r4”或者“23.23.11.23.123”
這都是不合法的IP地址
例如
輸入:192.41.6.20
輸出:0xC0290614
輸入:257.32.23.1
輸出:Error
解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')
解2:
def change(lis):
if len(lis)!=4:
return 'Error'
try: # 判斷字符串是否存在非數(shù)字
lis=[int(i) for i in lis]
except:
return 'Error'
for i in lis:
if i0 or i>255: # 判斷ip地址是否合法
return 'Error'
temp='0x' #記錄16進(jìn)制數(shù)
for i in lis:
a=hex(int(i))[2:].upper().rjust(2,'0') #轉(zhuǎn)換為16進(jìn)制
# if len(a)!=2:
# a='0'+a
temp+=a
return temp
s=list(map(str,input().split('.')))
print(change(s))
解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)
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
您可能感興趣的文章:- 用python查找統(tǒng)一局域網(wǎng)下ip對(duì)應(yīng)的mac地址
- Python3獲取電腦IP、主機(jī)名、Mac地址的方法示例
- python獲取本機(jī)mac地址和ip地址的方法
- python生成隨機(jī)mac地址的方法
- Python生成隨機(jī)MAC地址
- python通過(guò)scapy獲取局域網(wǎng)所有主機(jī)mac地址示例
- python IP地址轉(zhuǎn)整數(shù)
- python 輸入字符串生成所有有效的IP地址(LeetCode 93號(hào)題)
- 基于python實(shí)現(xiàn)查詢ip地址來(lái)源
- python如何判斷IP地址合法性
- Python中IP地址處理IPy模塊的方法
- 如何用Python獲取計(jì)算機(jī)名,ip地址,mac地址