python获取网络信息_在Python中获取网络地址和网络掩码

在Python脚本中获取主机IP地址可以使用socket模块,但如何获取网络地址和网络掩码呢?通过调用fcntl.ioctl与struct.pack结合可以获取网络地址。例如,对于Linux系统,可以使用`iface = "eth0"`,然后使用`socket.inet_ntoa(fcntl.ioctl(socket.socket(socket.AF_INET, socket.SOCK_DGRAM), 35099, struct.pack('256s', iface))[20:24])`来获取。若需要CIDR格式(如'128.1.2.0/20'),可以利用netaddr库的IPNetwork进行转换。" 102649908,8588355,Springboot多模块项目配置与构建详解,"['Spring Boot', '模块化开发', 'Maven', '项目构建']
摘要由CSDN通过智能技术生成

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.

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()

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.

Example:

128.1.2.0/20

I can actually find it under inet when I run ip addr. Any easy way to get this information in Python?

解决方案

For Linux try

iface = "eth0"

socket.inet_ntoa(fcntl.ioctl(socket.socket(socket.AF_INET, socket.SOCK_DGRAM),

35099, struct.pack('256s', iface))[20:24])

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

For example netaddr:

>> from netaddr import IPNetwork

>> print str(IPNetwork('1.2.3.4/255.255.255.0').cidr)

1.2.3.0/24

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值