python3获取自己ip

时间:2021-08-08 18:32:39
 1 import urllib.request,re
 2 import wmi
 3 
 4 def getMyIp():
 5     try:
 6         rawTxt = urllib.request.urlopen('http://2019.ip138.com/ic.asp', timeout = 60).read()
 7     except urllib.request.HTTPError as e:
 8         print("Error Code", e.code, e.read())
 9         return str(e.code), str(e.read())
10     except urllib.request.URLError as e:
11         print("Failed to reach the server ", e.reason)
12         return "URLError", str(e.reason)
13     except Exception as e:
14         print("Exception", e)
15         return "Exception", str(e)
16     rawTxt = rawTxt.decode('gb2312')
17     addr = re.search(u'来自:.*</center>', rawTxt).group(0)
18     addr = addr[3:len(addr)-9]
19     print(addr)
20     ip = re.search('\d+\.\d+\.\d+\.\d+', rawTxt).group(0)
21     print(ip)
22     return ip, addr
23 
24 getMyIp()