在 Python 中检索网络掩码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/936444/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Retrieving network mask in Python
提问by Scott
How would one go about retrieving a network device's netmask (In Linux preferably, but if it's cross-platform then cool)? I know how in C on Linux but I can't find a way in Python -- minus ctypes perhaps. That or parsing ifconfig. Any other way?
如何检索网络设备的网络掩码(最好在 Linux 中,但如果它是跨平台的,那么很酷)?我知道如何在 Linux 上使用 C,但我在 Python 中找不到方法——也许减去 ctypes。那还是解析ifconfig。还有什么办法吗?
ioctl(socknr, SIOCGIFNETMASK, &ifreq) // C version
回答by Ben Blank
回答by Vinko Vrsalovic
Did you look here?
你看这里了吗?
http://docs.python.org/library/fcntl.html
http://docs.python.org/library/fcntl.html
This works for me in python 2.5.2 on Linux. Was finishing it when Ben got ahead, but still here it goes (sad to waste the effort :-) ):
这在 Linux 上的 python 2.5.2 中对我有用。当 Ben 领先时正在完成它,但它仍然存在(遗憾的是浪费了努力:-)):
vinko@parrot:~$ more get_netmask.py
# get_netmask.py by Vinko Vrsalovic 2009
# Inspired by http://code.activestate.com/recipes/439093/
# and http://code.activestate.com/recipes/439094/
# Code: 0x891b SIOCGIFNETMASK
import socket
import fcntl
import struct
import sys
def get_netmask(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(s.fileno(), 0x891b, struct.pack('256
s',ifname))[20:24])
if len(sys.argv) == 2:
print get_netmask(sys.argv[1])
vinko@parrot:~$ python get_netmask.py lo
255.0.0.0
vinko@parrot:~$ python get_netmask.py eth0
255.255.255.0
回答by Steven Winfield
The netifaces
module deserves a mention here. Straight from the docs:
该netifaces
模块在这里值得一提。直接来自文档:
>>> netifaces.interfaces()
['lo0', 'gif0', 'stf0', 'en0', 'en1', 'fw0']
>>> addrs = netifaces.ifaddresses('en0')
>>> addrs[netifaces.AF_INET]
[{'broadcast': '10.15.255.255', 'netmask': '255.240.0.0', 'addr': '10.0.1.4'}, {'broadcast': '192.168.0.255', 'addr': '192.168.0.47'}]
Works on Windows, Linux, OS X, and probably other UNIXes.
适用于 Windows、Linux、OS X 和其他 UNIX。
回答by Roman Lisagor
You can use this library: http://github.com/rlisagor/pynetlinux. Note: I'm the author of the library.
你可以使用这个库:http: //github.com/rlisagor/pynetlinux。注意:我是图书馆的作者。
回答by Christian Tremblay
I had the idea to rely on subprocess to use a simple ifconfig (Linux) or ipconfig (windows) request to retrieve the info (if the ip is known). Comments welcome:
我的想法是依靠子进程使用简单的 ifconfig (Linux) 或 ipconfig (windows) 请求来检索信息(如果 ip 已知)。 欢迎评论:
WINDOWS
视窗
ip = '192.168.1.10' #Example
proc = subprocess.Popen('ipconfig',stdout=subprocess.PIPE)
while True:
line = proc.stdout.readline()
if ip.encode() in line:
break
mask = proc.stdout.readline().rstrip().split(b':')[-1].replace(b' ',b'').decode()
UNIX-Like
类 UNIX
ip = '192.168.1.10' #Example
proc = subprocess.Popen('ifconfig',stdout=subprocess.PIPE)
while True:
line = proc.stdout.readline()
if ip.encode() in line:
break
mask = line.rstrip().split(b':')[-1].replace(b' ',b'').decode()
IP is retrieved using a socket connection to the web and using getsockname()[0]
使用套接字连接到网络并使用 getsockname()[0]
回答by Aliaksei Ramanau
In Windows this piece of code may be useful:
在 Windows 中,这段代码可能很有用:
import os
import sys
import _winreg
def main():
adapter_list_key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,
r'SOFTWARE\Microsoft\Windows NT\CurrentVersion\NetworkCards')
adapter_count = _winreg.QueryInfoKey(adapter_list_key)[0]
for i in xrange(adapter_count):
sub_key_name = _winreg.EnumKey(adapter_list_key, i)
adapter_key = _winreg.OpenKey(adapter_list_key, sub_key_name)
(adapter_service_name, _) = _winreg.QueryValueEx(adapter_key, "ServiceName")
(description, _) = _winreg.QueryValueEx(adapter_key, "Description")
adapter_registry_path = os.path.join(r'SYSTEM\ControlSet001\Services',
adapter_service_name, "Parameters", "Tcpip")
adapter_service_key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,
adapter_registry_path)
(subnet_mask, _) = _winreg.QueryValueEx(adapter_service_key, "SubnetMask")
(ip_address, _) = _winreg.QueryValueEx(adapter_service_key, "IpAddress")
sys.stdout.write("Name: %s\n" % adapter_service_name)
sys.stdout.write("Description: %s\n" % description)
sys.stdout.write("SubnetMask: %s\n" % subnet_mask)
sys.stdout.write("IpAdress: %s\n" % ip_address)
if __name__ == "__main__":
main()
Get network adapters list from HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\NetworkCards
registry key and than extract more info about each adapter from HKLM\SYSTEM\ControlSet001\Services\{adapter_guid}\Parameters\Tcpip
key.
从HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\NetworkCards
注册表项中获取网络适配器列表,然后从注册表项中提取有关每个适配器的更多信息HKLM\SYSTEM\ControlSet001\Services\{adapter_guid}\Parameters\Tcpip
。
I test it on Windows XP with 2 virtual adapters, it works fine. Should work in 2000, 2003, and Vista too.
我在带有 2 个虚拟适配器的 Windows XP 上对其进行了测试,它运行良好。应该也适用于 2000、2003 和 Vista。
回答by belabrinel
Using the python pyroute2 library you can get all network element attributes:
使用 pythonpyrute2 库,您可以获得所有网络元素属性:
from pyroute2 import IPRoute
ip = IPRoute()
info = [{'iface': x['index'], 'addr': x.get_attr('IFA_ADDRESS'), 'mask': x['prefixlen']} for x in ip.get_addr()]
More information available here:http://pyroute2.org/pyroute2-0.3.14p4/iproute.html
此处提供更多信息:http: //pyroute2.org/pyroute2-0.3.14p4/iproute.html