获取本机的ip地址、子网掩码、网关 使用python实现
时间: 2024-11-22 19:46:58 浏览: 65
在Python中,我们可以利用os模块和socket模块来获取本地计算机的IP地址、子网掩码和默认网关。以下是简单的示例代码:
```python
import os
import subprocess
def get_network_info():
# 获取IP地址
ip_address = subprocess.check_output(['hostname', '-I']).decode('utf-8').split()[0]
# 获取子网掩码
ipconfig_cmd = 'ipconfig | findstr /B "IPv4 Address" | findstr /B "Subnet Mask"'
subnet_mask = subprocess.check_output(ipconfig_cmd, shell=True).decode('utf-8').split()[-1][:-1] # 去除换行符和括号
# 获取默认网关
gateway_cmd = 'route -n | findstr "Default Gateway"'
gateway_output = subprocess.check_output(gateway_cmd, shell=True).decode('utf-8')
gateway = None
for line in gateway_output.split('\n'):
if 'Default Gateway' in line:
gateway = line.strip().split()[1]
return ip_address, subnet_mask, gateway
# 调用函数并打印结果
ip, subnet, gw = get_network_info()
print(f"IP 地址: {ip}")
print(f"子网掩码: {subnet}")
print(f"网关: {gw}")
阅读全文