SHARE
TWEET

Untitled

a guest Jun 18th, 2019 78 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3.  
  4. from flask import Flask, request, jsonify
  5. import logging.config
  6. import struct
  7. import socket
  8.  
  9. logging.basicConfig(level=logging.DEBUG)
  10. logger = logging.getLogger(__name__)
  11.  
  12. app = Flask(__name__)
  13.  
  14. def ip2int(addr):
  15.     return struct.unpack("!I", socket.inet_aton(addr))[0]
  16.  
  17. def int2ip(addr):
  18.     return socket.inet_ntoa(struct.pack("!I", addr))
  19.  
  20. @app.route('/cidr_range/<string:addr>/<int:mask>', methods=['GET'])
  21. def get_range(addr, mask):
  22.  
  23.     addr = addr.split('_')
  24.  
  25.     if len(addr) != 4:
  26.         return jsonify({'error': 'Invalid cidr'})
  27.  
  28.     for i in addr:
  29.         if int(i) > 255:
  30.             return jsonify({'error': 'Invalid cidr'})
  31.    
  32.     addr = '.'.join(addr)
  33.  
  34.     first = ip2int(addr) & (-1 << 32 - mask)
  35.     last = first + pow(2, 32 - mask) - 1
  36.  
  37.     return jsonify({'first_ip': int2ip(first+1), 'last_ip': int2ip(last)})
  38.  
  39.  
  40. @app.route('/cidr/ip/<string:addr_1>/in_range/<string:addr_2>/<int:mask>', methods=['GET'])
  41. def check_in_range(addr_1, addr_2, mask):
  42.  
  43.     addr_1 = addr_1.split('_')
  44.     addr_2 = addr_2.split('_')
  45.  
  46.     if len(addr_1) != 4 or len(addr_2) != 4:
  47.         return jsonify({'error': 'Invalid cidr'})
  48.  
  49.     for i in addr_1:
  50.         if int(i) > 255:
  51.             return jsonify({'error': 'Invalid cidr'})
  52.  
  53.     for i in addr_2:
  54.         if int(i) > 255:
  55.             return jsonify({'error': 'Invalid cidr'})
  56.  
  57.     addr_1 = '.'.join(addr_1)
  58.     addr_2 = '.'.join(addr_2)
  59.  
  60.     first = ip2int(addr_2) & (-1 << 32 - mask)
  61.     last = first + pow(2, 32 - mask) - 1
  62.  
  63.     if ip2int(addr_1) > first and ip2int(addr_1) < last:
  64.         return jsonify({'result': 'True'})
  65.     else:
  66.         return jsonify({'result': 'False'})
  67.  
  68.  
  69. if __name__ == "__main__":
  70.     app.run(port=5000)
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top