Python 3:根据 CIDR 表示法创建可能的 IP 地址列表

发布于 2024-08-15 19:06:38 字数 289 浏览 12 评论 0原文

我接到的任务是在 python (3.1) 中创建一个函数,该函数将采用 CIDR 表示法并返回可能的 IP 地址列表。我浏览了 python.org 并发现了这个: http://docs.python.org/dev/py3k/library/ipaddr.html

但我还没有看到任何可以满足这一需求的东西...如果有人愿意为我提供任何帮助,我将非常感激。提前致谢。 :-)

I have been handed the task of creating a function in python (3.1) that will take a CIDR notation and return the list of possible ip addresses. I have looked around python.org and found this:
http://docs.python.org/dev/py3k/library/ipaddr.html

but i haven't seen anything that will fill this need... I would be very grateful for any assistance anyone cares to kick my way. thanks in advance. :-)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

你与昨日 2024-08-22 19:06:38

在 Python 3 中就像这样简单

>>> import ipaddress
>>> [str(ip) for ip in ipaddress.IPv4Network('192.0.2.0/28')]
['192.0.2.0', '192.0.2.1', '192.0.2.2',
'192.0.2.3', '192.0.2.4', '192.0.2.5',
'192.0.2.6', '192.0.2.7', '192.0.2.8',
'192.0.2.9', '192.0.2.10', '192.0.2.11',
'192.0.2.12', '192.0.2.13', '192.0.2.14',
'192.0.2.15']

In Python 3 as simple as

>>> import ipaddress
>>> [str(ip) for ip in ipaddress.IPv4Network('192.0.2.0/28')]
['192.0.2.0', '192.0.2.1', '192.0.2.2',
'192.0.2.3', '192.0.2.4', '192.0.2.5',
'192.0.2.6', '192.0.2.7', '192.0.2.8',
'192.0.2.9', '192.0.2.10', '192.0.2.11',
'192.0.2.12', '192.0.2.13', '192.0.2.14',
'192.0.2.15']
青衫儰鉨ミ守葔 2024-08-22 19:06:38

如果您不习惯使用内置模块,可以使用一个名为 netaddr 的项目这是我用于处理 IP 网络的最佳模块。

请查看IP 教程,其中说明了使用网络和辨别他们的IP。简单的例子:

>>> from netaddr import IPNetwork
>>> for ip in IPNetwork('192.0.2.0/23'):
...    print '%s' % ip
...
192.0.2.0
192.0.2.1
192.0.2.2
192.0.2.3
...
192.0.3.252
192.0.3.253
192.0.3.254
192.0.3.255

If you aren't married to using the built-in module, there is a project called netaddr that is the best module I have used for working with IP networks.

Have a look at the IP Tutorial which illustrates how easy it is working with networks and discerning their IPs. Simple example:

>>> from netaddr import IPNetwork
>>> for ip in IPNetwork('192.0.2.0/23'):
...    print '%s' % ip
...
192.0.2.0
192.0.2.1
192.0.2.2
192.0.2.3
...
192.0.3.252
192.0.3.253
192.0.3.254
192.0.3.255
一腔孤↑勇 2024-08-22 19:06:38

我宁愿做一点数学运算,也不愿安装外部模块,没有人和我有同样的品味吗?

#!/usr/bin/env python
# python cidr.py 192.168.1.1/24

import sys, struct, socket

(ip, cidr) = sys.argv[1].split('/')
cidr = int(cidr) 
host_bits = 32 - cidr
i = struct.unpack('>I', socket.inet_aton(ip))[0] # note the endianness
start = (i >> host_bits) << host_bits # clear the host bits
end = start | ((1 << host_bits) - 1)

# excludes the first and last address in the subnet
for i in range(start, end):
    print(socket.inet_ntoa(struct.pack('>I',i)))

I would prefer to do a little math rather than to install an external module, no one has the same taste with me?

#!/usr/bin/env python
# python cidr.py 192.168.1.1/24

import sys, struct, socket

(ip, cidr) = sys.argv[1].split('/')
cidr = int(cidr) 
host_bits = 32 - cidr
i = struct.unpack('>I', socket.inet_aton(ip))[0] # note the endianness
start = (i >> host_bits) << host_bits # clear the host bits
end = start | ((1 << host_bits) - 1)

# excludes the first and last address in the subnet
for i in range(start, end):
    print(socket.inet_ntoa(struct.pack('>I',i)))
云朵有点甜 2024-08-22 19:06:38

您是否检查过 iptools?这似乎是一个相当不错的选择。

Have you checked out iptools? It seems to be a fairly good fit.

陈年往事 2024-08-22 19:06:38

如果你对 python 逻辑不感兴趣,我们可以使用 Python 的 ipaddress lib 来获取它。除此之外,上述解决方案就足够了。

import ipaddress
  
def get_ip_from_subnet(ip_subnet):

    ips= ipaddress.ip_network(ip_subnet)
    ip_list=[str(ip) for ip in ips]
    return ip_list

ip_subnet= "192.168.2.0/24"
print(get_ip_from_subnet(ip_subnet))

We can get this by using ipaddress lib of Python if you are not interested in playing with python logics. Else above solutions are enough.

import ipaddress
  
def get_ip_from_subnet(ip_subnet):

    ips= ipaddress.ip_network(ip_subnet)
    ip_list=[str(ip) for ip in ips]
    return ip_list

ip_subnet= "192.168.2.0/24"
print(get_ip_from_subnet(ip_subnet))
虫児飞 2024-08-22 19:06:38

它不在文档中,但浏览源代码表明 ipaddr 实现了 __iter__ 和 iterhosts,这正是您想要的。


呃,没关系。

  1. 看起来 ipaddr.py 已在 3.1 beta 中添加到 stdlib,但在 3.1 rc 中被删除。
  2. 我正在查看原始 ipaddr.py 的来源,它似乎有与 python.org 上的副本分开发展。

你可以将后者捆绑在一起。

It's not in the documentation, but browsing the source suggests that ipaddr implements __iter__ and iterhosts, which is exactly what you want.


Err, nevermind.

  1. It looks like ipaddr.py was added to stdlib in 3.1 beta, but removed by 3.1 rc.
  2. I was looking at the sources from the original ipaddr.py, which seems to have evolved separately from the copy at python.org.

You could just bundle the latter.

放低过去 2024-08-22 19:06:38

下面的代码将根据提供的 IP 和子网生成 IP 范围。展开 CIDR 表示法,例如 (255.255.255.0)

from netaddr import *

def getFirstIp(ipAddress,subnet):
  ipBin = IPNetwork(ipAddress).ip.bits().split('.')
  subBin = IPNetwork(subnet).ip.bits().split('.')
  zipped = zip(ipBin,subBin)
  netIdList = []
  for octets in zipped:
    netIdList.append(''.join(str(b) for b in (map((lambda x: int(x[0])*int(x[1])),zip(list(octets[0]),list(octets[1]))))))
  firstIp = ''
  firstIp = '.'.join(str(int(oct,2)) for oct in netIdList)
  return firstIp


def getLastIp(ipAddress,subnet):
  ipBin = IPNetwork(ipAddress).ip.bits().split('.')
  subBin = IPNetwork(subnet).ip.bits().split('.')
  #print ipBin
  #print subBin
  revsubBin = []
  for octets in subBin:
    revB = ''.join('1' if(b == '0') else '0' for b in octets)
    revsubBin.append(revB)
  zipped = zip(ipBin,revsubBin)
  netIdList = []
  for octets in zipped:
    netIdList.append(''.join(str(b) for b in (map((lambda x: 0 if(int(x[0]) == 0 and int(x[1]) == 0) else 1),zip(list(octets[0]),list(octets[1]))))))
  #print netIdList
  lastIp = ''
  lastIp = '.'.join(str(int(oct,2)) for oct in netIdList)
  return lastIp

def getRangeOfIps(firstIp,lastIp):
  start= int(IPAddress(firstIp))
  end = int(IPAddress(lastIp))
  ipList = []
  for ip in range(start,end+1):
    ipList.append(str(IPAddress(ip)))
  return ipList

def manipulateIP():
 firstIp = getFirstIp(ipAddress,subnet)
 lastIp = getLastIp(ipAddress,subnet)
 ipList = getRangeOfIps(firstIp,lastIp)  
 print ipList 

Below code will generate range of IPs on providing IP and subnet. Expand the CIDR notation like(255.255.255.0)

from netaddr import *

def getFirstIp(ipAddress,subnet):
  ipBin = IPNetwork(ipAddress).ip.bits().split('.')
  subBin = IPNetwork(subnet).ip.bits().split('.')
  zipped = zip(ipBin,subBin)
  netIdList = []
  for octets in zipped:
    netIdList.append(''.join(str(b) for b in (map((lambda x: int(x[0])*int(x[1])),zip(list(octets[0]),list(octets[1]))))))
  firstIp = ''
  firstIp = '.'.join(str(int(oct,2)) for oct in netIdList)
  return firstIp


def getLastIp(ipAddress,subnet):
  ipBin = IPNetwork(ipAddress).ip.bits().split('.')
  subBin = IPNetwork(subnet).ip.bits().split('.')
  #print ipBin
  #print subBin
  revsubBin = []
  for octets in subBin:
    revB = ''.join('1' if(b == '0') else '0' for b in octets)
    revsubBin.append(revB)
  zipped = zip(ipBin,revsubBin)
  netIdList = []
  for octets in zipped:
    netIdList.append(''.join(str(b) for b in (map((lambda x: 0 if(int(x[0]) == 0 and int(x[1]) == 0) else 1),zip(list(octets[0]),list(octets[1]))))))
  #print netIdList
  lastIp = ''
  lastIp = '.'.join(str(int(oct,2)) for oct in netIdList)
  return lastIp

def getRangeOfIps(firstIp,lastIp):
  start= int(IPAddress(firstIp))
  end = int(IPAddress(lastIp))
  ipList = []
  for ip in range(start,end+1):
    ipList.append(str(IPAddress(ip)))
  return ipList

def manipulateIP():
 firstIp = getFirstIp(ipAddress,subnet)
 lastIp = getLastIp(ipAddress,subnet)
 ipList = getRangeOfIps(firstIp,lastIp)  
 print ipList 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文