Python 生成 ip 地址

2018-10-19 09:56:37 +08:00
 Na1Kh2

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 有哪些库可以解决这个问题么?

4109 次点击
所在节点    Python
13 条回复
stamaimer
2018-10-19 12:13:02 +08:00
排个版
no1xsyzy
2018-10-19 12:49:22 +08:00
IP 段不连续,不符合规范,唯有用 random 库手撸
alixali
2018-10-19 13:53:21 +08:00
ValueError: only one '-' allowed in IP Address
Na1Kh2
2018-10-19 14:56:23 +08:00
@stamaimer
@alixali
emmmmm 是这样的
我要按输入的语句生成 ip 地址,只是拿 IPy 举了个栗子
比如说我输入
172.10.100-101.1-3
生成
172.10.100.1
172.10.100.2
172.10.100.3
172.10.101.1
172.10.101.2
172.10.101.3
------------------------
撸了一中午 还没写出来
@no1xsyzy
Na1Kh2
2018-10-19 15:02:17 +08:00
我现在的想法是:
把输入的字符串 split('.')分割
把分割出的 list 循环读取出来
读取出来的内容用 split('-')分割
------
上面这些都写出来了
但是组合方法我实在是写不出来了 没有头绪
no1xsyzy
2018-10-19 15:12:52 +08:00
不要老想着这是一个 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("-"))]])]
no1xsyzy
2018-10-19 15:14:28 +08:00
#5 看起来需要重练基本功……
Na1Kh2
2018-10-19 15:16:14 +08:00
@no1xsyzy emmm 谢了大佬
Na1Kh2
2018-10-19 15:16:31 +08:00
@no1xsyzy 手动委屈.gif
hgw514
2018-10-19 17:11:20 +08:00
https://docs.python.org/3/library/ipaddress.html#ip-network-definitions
Python3 标准库 ipaddress 可以处理 IP 网段,考虑用 CIDR 格式划分子网?
pythonnoob
2018-10-20 10:26:08 +08:00
基本功太差
pythonnoob
2018-10-20 11:01:53 +08:00
随手写了一个,没考虑效率方面的问题:
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)
pythonnoob
2018-10-20 11:04:33 +08:00
图: https://s1.ax1x.com/2018/10/20/i01I00.jpg
注:也没考虑捣乱的情况

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/499013

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX