简体   繁体   English

在Python中获取网络地址和网络掩码

[英]Get network address and network mask in Python

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. 在我的Python脚本中,我需要检索运行脚本的机器的IP地址及其网络地址和网络字节。

As for the IP address, I found the solution in the archive: 至于IP地址,我在档案中找到了解决方案:

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("www.google.com",80))
myAddress = (s.getsockname()[0])
s.close()

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. 我需要以$NetworkAddress/$NetworkBytes格式将此信息放入tcpdump的过滤器中,如果这有帮助的话。

Example: 例:

128.1.2.0/20

I can actually find it under inet when I run ip addr . 当我运行ip addr时,我实际上可以在inet下找到它。 Any easy way to get this information in Python? 在Python中获取此信息的任何简单方法?

For Linux try 对于Linux试试

iface = "eth0"
socket.inet_ntoa(fcntl.ioctl(socket.socket(socket.AF_INET, socket.SOCK_DGRAM), 
                             35099, struct.pack('256s', iface))[20:24])

or http://github.com/rlisagor/pynetlinux http://github.com/rlisagor/pynetlinux

(as suggested here: Retrieving network mask in Python ) (如此处所示: 在Python中检索网络掩码

For Linux, Windows and MacOS consider http://alastairs-place.net/projects/netifaces/ 对于Linux,Windows和MacOS,请考虑http://alastairs-place.net/projects/netifaces/

Update: 更新:

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 如果你需要cidr(比如'128.1.2.0/20'),你可以使用任何相关的库: http ://pypi.python.org/pypi?%3Aaction = search&term = cidr&subsmit = search

For example netaddr : 例如netaddr

>> from netaddr import IPNetwork
>> print str(IPNetwork('1.2.3.4/255.255.255.0').cidr)
1.2.3.0/24

You can retrieve any ip-related info with pyroute2 module: 您可以使用pyroute2模块检索任何与ip相关的信息:

from pyroute2 import IPDB
ip = IPDB()
print(ip.interfaces['em1'].ipaddr)
ip.release()

Or as a variant: 或作为变体:

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()]
ip.close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM