从我的计算机python中提取子网掩码
亲爱的,我计划提取我的子网掩码,我使用了下面的代码,但是子网掩码总是255.255.255.255,这是错误的从我的计算机python中提取子网掩码,python,python-3.x,subnet,python-netifaces,Python,Python 3.x,Subnet,Python Netifaces,亲爱的,我计划提取我的子网掩码,我使用了下面的代码,但是子网掩码总是255.255.255.255,这是错误的 import socket # Import socket module import netifaces def get_ip_address(): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("8.8.8.8", 80)) My_ip=s.get
import socket # Import socket module
import netifaces
def get_ip_address():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
My_ip=s.getsockname()[0]
s.close()
return My_ip
def main():
#print(netifaces.interfaces())
for i in netifaces.interfaces():
try:
# Address
print("IP Address: ", netifaces.ifaddresses(i)[netifaces.AF_INET][0]['addr'])
print("Mask: ", netifaces.ifaddresses(i)[netifaces.AF_INET][0]['netmask'])
print("Gateway: ", netifaces.gateways()['default'][netifaces.AF_INET][0])
except:pass
# This is the IP address of the GateWay
if __name__ == '__main__': main()
代码的输出为:
IPAddress: 192.168.1.4
Mask: 255.255.255.255
Gateway: 192.168.1.1
IP Address: 192.168.231.1
Mask: 255.255.255.255
Gateway: 192.168.1.1
IP Address: 192.168.116.1
Mask: 255.255.255.255
Gateway: 192.168.1.1
IP Address: 10.255.90.137
Mask: 255.255.255.255
Gateway: 192.168.1.1
IP Address: 127.0.0.1
Mask: 255.255.255.255
Gateway: 192.168.1.1
CMD上IPconfig/all的输出:
ipconfig/all
在
Windows
上有netifaces
的替代方案。您可以使用wmic
检索接口信息wmic
具有使用XML的机器可读输出选项:
wmic nic get /format:rawxml
可以使用python示例。代码对我来说很好。你能显示你的输出吗,也许还有来自ifconfig/ipconfig的输出?我在主帖子中添加了输出,谢谢@stephernauch
wmic nic get /format:rawxml