import ipaddress from functools import reduce def get_client_agent(request, truncate=True): """ The simplest way to get client device. If you want to extend this function, try this: pip install django-user-agents `django-user-agents` is base on `ua-parser` `user-agents`, """ user_agent = request.META.get('HTTP_USER_AGENT', '') if truncate: user_agent = user_agent[:255] return user_agent def get_client_ip(request): # FIX ME: It's dangerous to get ip from `HTTP_X_Forwarded_For` by this way. ip = request.META.get('HTTP_X_FORWARDED_FOR', '').split(',')[0] if ip: return ip ip = request.META.get('HTTP_X_REAL_IP') if ip: return ip return request.META.get('REMOTE_ADDR') def ip_into_int(ip): return reduce(lambda x, y: (x << 8) + y, map(int, ip.split('.'))) def is_internal_ip(ip): if ip == '127.0.0.1': return True ip = ip_into_int(ip) net_a = ip_into_int('10.255.255.255') >> 24 net_b = ip_into_int('172.31.255.255') >> 20 net_c = ip_into_int('192.168.255.255') >> 16 return ip >> 24 == net_a or ip >> 20 == net_b or ip >> 16 == net_c def check_ip_in_allowlist(ip, allowlist): # :ip 192.168.1.1 # :allowlist ['192.168.1.1', '192.168.0.0/16'] # Return `None` if not match, return matched ip-network if test passed. if not allowlist: return ip user_ip = ipaddress.ip_address(ip) for allow_ip in allowlist: if user_ip in ipaddress.ip_network(allow_ip, strict=False): return allow_ip