ip获取-py

ip获取-py

四月 06, 2020
  • 用于获取用户当前的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
27
28
29
30
31
32
33
34
35
36
import urllib.request
import subprocess
import socket
import re
import os
import requests, bs4, re, os
from lxml import etree

child=subprocess.Popen("ipconfig", shell=True, stdout = subprocess.PIPE)
out=child.communicate();#保存ipconfig中的所有信息

ipv6_pattern='(([a-f0-9]{1,4}:){7}[a-f0-9]{1,4})'
m=re.findall(ipv6_pattern,str(out));
address=m[1][0]
#print('临时ipv6地址:'+address)
ipv4_pattern='(([0-9]{1,3}.){3}[0-9]{1,3})'
m2=re.findall(ipv4_pattern,str(out))
for i in m2:
if str(i[0]).find('192.168') == 0 and str(i[0]) != '192.168.1.1':
ipv4 = i[0]
url = 'https://ip.cn/'
response = requests.get(url)
soup = bs4.BeautifulSoup(response.text, "html.parser")
comic = soup.select('p')
s_ipv4_out =str(comic[1])
pos = s_ipv4_out.find('Your IP')
s_now_ipv4_out=s_ipv4_out[pos+16:]
pos2 = s_now_ipv4_out.find('<')


os.system('cls')
print('临时ipv6地址:'+address)
print('本地ipv4地址:'+ipv4)
print('外网ip:'+s_now_ipv4_out[:pos2])
print('')
os.system('pause')