
from IPy import IP IP('172.10.250-254.250-254') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/lib/python2.7/site-packages/IPy.py", line 242, in init raise ValueError("only one '-' allowed in IP Address") ValueError: only one '-' allowed in IP Address</module></stdin>
IPy 好像不支持这种生成方式,Python 有哪些库可以解决这个问题么?
1 stamaimer 2018 年 10 月 19 日 via iPhone 排个版 |
2 no1xsyzy 2018 年 10 月 19 日 IP 段不连续,不符合规范,唯有用 random 库手撸 |
3 alixali 2018 年 10 月 19 日 ValueError: only one '-' allowed in IP Address |
4 Na1Kh2 OP |
5 Na1Kh2 OP 我现在的想法是: 把输入的字符串 split('.')分割 把分割出的 list 循环读取出来 读取出来的内容用 split('-')分割 ------ 上面这些都写出来了 但是组合方法我实在是写不出来了 没有头绪 |
6 no1xsyzy 2018 年 10 月 19 日 不要老想着这是一个 IP 地址,就结束了: lambda x: ["%d.%d.%d.%d"%d for d in itertools.product(*[range(m,n+1) for s in x.split(".") for m,n,*_ in [map(int, (s+"-"+s).split("-"))]])] |
7 no1xsyzy 2018 年 10 月 19 日 #5 看起来需要重练基本功…… |
10 hgw514 2018 年 10 月 19 日 https://docs.python.org/3/library/ipaddress.html#ip-network-definitions Python3 标准库 ipaddress 可以处理 IP 网段,考虑用 CIDR 格式划分子网? |
11 pythonnoob 2018 年 10 月 20 日 via Android 基本功太差 |
12 pythonnoob 2018 年 10 月 20 日 随手写了一个,没考虑效率方面的问题: def create_ip_address(one, two, three, four): int_list = [] for i in one, two, three, four: if isinstance(i, int): i = [i] i_len = len(i) if i_len == 1: int_list.append(i) elif i_len == 2: int_list.append(range(i[0], i[1]+1)) else: raise ValueError('元组内只能有 1~2 个数字') ip_list = [] for s in int_list: s_list = [str(w) for w in s] if not ip_list: ip_list = s_list else: ip_list = ['.'.join([o, p]) for p in s_list for o in ip_list] return ip_list if __name__ == '__main__': test_create = create_ip_address(1, (3, 50), (5, 6), (7, 8)) print(len(test_create), test_create) |
13 pythonnoob 2018 年 10 月 20 日 图: https://s1.ax1x.com/2018/10/20/i01I00.jpg 注:也没考虑捣乱的情况 |