windows系统获取本机IP地址

 1 #!/usr/bin
 2 # _*_ coding: UTF-8 _*_
 3 # Copyright (c) 2021 GengYu.All rights reserved
 4 # @Create by gengyu
 5 # @Create Time :2021/12/6
 6 # @File Name : get_ip
 7 # 打包命令 pyinstaller -F package\get_ip
 8 """
 9 
10 """
11 __author__ = 'Administrator'
12 import doctest
13 import os,re
14 
15 def gethost():
16     ipv4 = []
17     result = os.popen('ipconfig')
18     result_str = result.read()
19     ipv4_pattern = re.compile('ipv4 address[\.\s]+:\s[\d\.]+',re.I)
20     p = re.compile(r'\d+\.\d+\.\d+\.\d+')
21     ipv4_list = ipv4_pattern.findall(result_str)
22     for x in ipv4_list:
23         if p.search(x) is None:
24             print('IP Address could not be found!')
25             return
26         else:
27             ipv4.append(p.search(x)[0])
28     return ipv4
29 if __name__ == "__main__":
30     doctest.testmod()
31     ipv4 = gethost()
32     print(ipv4)

windows系统常见的获取IP地址有两种,但是结果都不太理想。

通过import socket来获取IP地址,在多网卡情况下,无法获取到想要的结果。

本程序可以获取本机所有IPv4地址,结果以列表形式返回。

 

posted @ 2021-12-06 21:09  火山的爱  阅读(615)  评论(0编辑  收藏  举报