【代码】查看本机内网IP和公网IP

前言

利用Python实现查看本机内网IP和公网IP,并显示公网IP的所属城市

源代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#!/usr/bin/python3

import os
import re

def get_private_ip():

res = os.popen("ifconfig")
arr = res.read().split("\n")

pattern = "^\tinet \d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"
result = []
for str_line in arr:
if re.findall(pattern, str_line) != []:
result.append(re.findall(pattern, str_line))
return result[1][0][6:]

def get_public_ip():

res = os.popen("curl -s myip.ipip.net")
arr = res.read().split("\n")

return arr[0][6:]

print(f"内网IP:{get_private_ip()}")
print(f"公网IP: {get_public_ip()}")

完成