Last active
October 17, 2022 06:52
-
-
Save wonderkun/f004103d75c0feac6317586e52f3c784 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python3 | |
from socket import inet_aton | |
from struct import unpack | |
from flask import Flask | |
import requests | |
import re | |
app = Flask(__name__) | |
def ip2long(ip_addr): | |
return unpack("!L", inet_aton(ip_addr))[0] | |
inner_net = [ | |
["127.255.255.255",24], | |
["172.31.255.255",20], | |
["10.255.255.255",24], | |
["192.168.255.255",16], | |
["0.255.255.255",24], | |
] | |
inner_ip_range = map( lambda x:[ ip2long(x[0]) >> x[1] << x[1] ,ip2long(x[0]) ], inner_net) | |
def is_inner_ipaddress(ip): | |
global inner_ip_range | |
ip = ip2long(ip) | |
for i in inner_ip_range: | |
print(i,ip) | |
if ip >= i[0] and ip <= i[1]: | |
return True | |
return False | |
@app.route('/<ip>') | |
def req(ip): | |
if not re.match(r"^((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})(\.((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})){3}$",ip): | |
return "invalid ip:{}".format(ip) | |
if not is_inner_ipaddress(ip): | |
return "valid ip:{}".format(ip) | |
else: | |
return "inner ip:{}".format(ip) | |
if __name__ == '__main__': | |
app.run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
开头我强调说是python2向python3迁移的时候发现了这段代码,那就是说明这个问题问题肯定是与python版本有关系了。
结果也是如此,这段代码在python2可以正常工作,但是到python3的时候就不行了,问题是出在这一行上:
inner_ip_range = map( lambda x:[ ip2long(x[0]) >> x[1] << x[1] ,ip2long(x[0]) ], inner_net)
map在python2的时候返回的是一个list:
map在python3的时候返回的是一个iterator:
迭代器被遍历一次之后就会被耗尽,所以第二次遍历不会有任何返回;
所以在python3环境下多次访问这个全局变量,只能第一次过滤生效,后续的都不会生效。其实自己跑一下这个代码就看出来了。