使用python直接运行获取本机的ipv4,ipv6,子网掩码,默认网关,不用ipconfig
时间: 2024-11-25 08:18:28 浏览: 50
在Python中,你可以通过第三方库如`psutil`和`netifaces`来获取网络信息,包括IPv4、IPv6、子网掩码和默认网关。以下是简单的步骤:
首先,你需要安装这两个库,如果尚未安装,可以使用pip安装:
```bash
pip install psutil netifaces
```
然后,你可以使用以下代码片段来获取这些信息:
```python
import psutil
import netifaces as ni
def get_network_info():
# 获取所有网络接口
interfaces = psutil.net_if_addrs()
def parse_ipv4(interface):
for ip in interface:
if ip.family == psutil.AF_INET:
return ip.address
def parse_ipv6(interface):
for ip in interface:
if ip.family == psutil.AF_INET6:
return ip.address
info = {}
for interface_name, addresses in interfaces.items():
try:
# IPv4
ipv4 = parse_ipv4(addresses)
if ipv4:
info["IPv4"] = ipv4
# IPv6
ipv6 = parse_ipv6(addresses)
if ipv6:
info["IPv6"] = ipv6
# 子网掩码
subnet_mask = ni.ifaddresses(interface_name)[ni.AF_INET][0]['netmask']
info["Subnet Mask"] = subnet_mask
# 默认网关
default_gw = ni.gateways()['default'][ni.AF_INET][1]
if default_gw and interface_name in default_gw:
info["Default Gateway"] = default_gw[interface_name]
except Exception as e:
print(f"Error retrieving information for {interface_name}: {e}")
return info
network_info = get_network_info()
print(network_info)
阅读全文