python:生成指定范围内的所有ip

Posted channy14

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python:生成指定范围内的所有ip相关的知识,希望对你有一定的参考价值。

生成指定范围内的所有ip

#codint:utf8
def get_side(pos, now):
    global begin, end
    global first, last                             #
    find_side = lambda begin, end, pos, fisrt, last, now: \\
        (pos == first[now] and begin[now + 1] or 1, pos == last[now] and end[now + 1] or 255)
    first[now + 1], last[now + 1] = find_side(begin, end, pos, first, last, now)
    # print first
    return range(first[now + 1], last[now + 1] + 1)
 
 
def gen_ip(ip):     
    global begin, end
    global first, last
    sides = ip.split(\'-\')
    begin = map(lambda x: int(x), sides[0].split(\'.\'))
    end = map(lambda x: int(x), sides[1].split(\'.\'))
    first[0] = begin[0]
    last[0] = end[0]
    ip_str = []   
 
    for pos_one in range(begin[0], end[0] + 1):
        for pos_two in get_side(pos_one, 0):
            for pos_three in get_side(pos_two, 1):
                for pos_four in get_side(pos_three, 2):
                    str = "%d.%d.%d.%d" % (pos_one, pos_two, pos_three, pos_four)
                    ip_str.append(str)
 
    return ip_str
if __name__ == \'__main__\':
    global begin, end
    global first, last, ips
    first = ["", "", "", ""]
    last = ["", "", "", ""]
    ips = gen_ip("120.76.0.0-120.79.255.255")
    print ips
View Code

 

 

生成指定范围内的IP段

#!/usr/local/bin/python
#-*- coding: UTF-8 -*-
#############################################################
# python 生成IP段
#############################################################
if __name__ == \'__main__\':
  result=file(\'test.txt\',\'w\')
  for IP1 in range(254,0,-1):
    for IP2 in range(254,0,-1):
      #for IP3 in range(254,0,-1):
        #for IP4 in range(254,0,-1):
          #print IP1,IP2
        abc= \'%s.%s.%s-%s.%s.%s\\n\' % (IP1,IP2,"1.1",
                    IP1,IP2,"255.255")
        result.write(abc)
  result.close()
View Code

 

以上是关于python:生成指定范围内的所有ip的主要内容,如果未能解决你的问题,请参考以下文章

python之随机数生成方法汇总

Python实现返回指定范围内的所有素数

SQL Server生成指定范围内的随机数

在python中生成给定范围内的所有日期

Mysql生成任意指定两时间范围内的日期列表

js如何生成指定范围内的随机数