10
16

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

FlaskでIP制限する

Posted at

flaskでIP制限をかける - Qiita

あったけれどマスクでかける。

from flask import Flask, request, abort
import ipaddress

app = Flask(__name__)


@app.route('/')
def hello_world():
    return 'Hello World!'


ALLOW_NETWORKS = ["10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "127.0.0.1"]


@app.before_request
def before_request():
    remote_addr = ipaddress.ip_address(request.remote_addr)
    app.logger.info(remote_addr)

    for allow_network in ALLOW_NETWORKS:
        ip_network = ipaddress.ip_network(allow_network)
        if remote_addr in ip_network:
            app.logger.info(ip_network)
            return
    return abort(403, 'access denied from your IP address')


if __name__ == '__main__':
    app.run()



10
16
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
16

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?