import socket
import os
import re
def get_host_ip():"""查询本机ip地址:return:"""try:s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)s.connect(('8.8.8.8',80))# 能提取出本机ip 通过本机ip提取出其他设置ip = s.getsockname()[0]# ip地址、子网掩码、默认网关、dns服务器baseinfo = os.popen('ipconfig/all')tempstream = baseinfo._streaminfostrs = tempstream.buffer.read().decode(encoding='gbk')infolists = infostrs.splitlines()validinfolist = []for index, value in enumerate(infolists):if ip in value:validinfolist = infolists[index: index+11]pattern = re.compile(r'\d+.\d+.\d+.\d+')for info in validinfolist:if '子网掩码' in info or 'Mask' in info :subnetmask = re.findall(pattern, info)[0]if '默认网关' in info or 'ateway' in info :defgateway = re.findall(pattern, info)[0]if '默认网关' in info or 'ateway' in info :defgateway = re.findall(pattern, info)[0]if 'DHCP 服务器' in info or 'DHCP Server' in info:dhcpserver = re.findall(pattern, info)[0]if 'DNS'in info :dnsserver = re.findall(pattern, info)[0]print(subnetmask)print(defgateway)print(defgateway)print(dnsserver)finally:s.close()return ipif __name__ == '__main__':print(get_host_ip())