在Python中获取网络地址和网络掩码 [英] Get network address and network mask in Python
问题描述
在我的Python脚本中,我需要检索运行脚本的机器的IP地址及其网络地址和网络字节。
In my Python script I need to retrieve both the IP address of the machine the script is running on and its network address and its network bytes.
至于IP地址,我在档案中找到了解决方案:
As for the IP address, I found the solution in the archive:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("www.google.com",80))
myAddress = (s.getsockname()[0])
s.close()
但我应该如何去寻找网络地址和网络字节?我需要将此信息放入tcpdump的过滤器中,格式为 $ NetworkAddress / $ NetworkBytes
,如果这有帮助的话。
But how should I go about finding network address and network bytes? I need to put this information into a filter for tcpdump in the format $NetworkAddress/$NetworkBytes
, if that helps at all.
示例:
128.1.2.0/20
当我运行 ip addr $ c $时,我实际上可以在
inet
下找到它C>。有什么简单的方法可以用Python获取这些信息吗?
I can actually find it under inet
when I run ip addr
. Any easy way to get this information in Python?
推荐答案
对于Linux试试
iface = "eth0"
socket.inet_ntoa(fcntl.ioctl(socket.socket(socket.AF_INET, socket.SOCK_DGRAM),
35099, struct.pack('256s', iface))[20:24])
或 http://github.com/rlisagor/pynetlinux
(as建议在这里:在Python中检索网络掩码)
对于Linux,Windows和MacOS,请考虑 http://alastairs-place.net/projects / netifaces /
For Linux, Windows and MacOS consider http://alastairs-place.net/projects/netifaces/
更新:
如果您需要cidr (如'128.1.2.0/20'),您可以使用任何相关的库: http://pypi.python.org/pypi?%3Aaction=search&term=cidr&submit=search
If you need cidr (like '128.1.2.0/20'), you can use any of the related libs: http://pypi.python.org/pypi?%3Aaction=search&term=cidr&submit=search
例如 netaddr
:
>> from netaddr import IPNetwork
>> print str(IPNetwork('1.2.3.4/255.255.255.0').cidr)
1.2.3.0/24
这篇关于在Python中获取网络地址和网络掩码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!