1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

WSL2におけるFlaskの起動ホストと接続可否一覧

Posted at

## はじめに
WindowsのWSL2の中で起動したFlaskアプリを起動した際に、Windowsから指定するURLが何なのかと思って調べてみた。

結論

昨今はWSL2のlocalhostは自動でWindowsのlocalhostにマッピングされるのであまり気にしなくても使えるらしい。

WSL2で起動したFlaskの host 指定値 接続元 接続例 挙動 補足
127.0.0.1 WSL内 http://127.0.0.1:5000 :white_check_mark: WSL内のローカルループバックアドレス
127.0.0.1 Windows側 http://127.0.0.1:5000 :white_check_mark: localhostForwarding=true(WSL構成ファイル .wslconfig で設定)で有効。無効化すると不可。
0.0.0.0 WSL内 http://127.0.0.1:5000 または http://:5000 :white_check_mark: 0.0.0.0は全インターフェースバインド。WSLのIPも含む。
0.0.0.0 Windows側 http://127.0.0.1:5000 :white_check_mark: Windowsの仮想スイッチとWSLのネットワーク連携が進化。ファイアウォール設定次第でブロックされることも。
0.0.0.0 Windows側 http://127.0.0.1:5000 または http://:5000 :white_check_mark: 上記同様
172.30.xx.xx (WSL IP) WSL内 http://172.30.xx.xx:5000 :white_check_mark: WSLの仮想ネットワークIP
172.30.xx.xx (WSL IP) Windows側 http://172.30.xx.xx:5000 :white_check_mark: Windows側からWSLのIPに直接アクセス可能

詳細

ソースコード

WSL内のFlaskアプリ
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
    return 'Hello, World!'
if __name__ == '__main__':
    # ここを切り替えていく
    app.run(host='0.0.0.0', port=5000, debug=True)
    # app.run(host='127.0.0.1', port=5000, debug=True)
    # app.run(host='172.30.44.147', port=5000, debug=True)
リクエスト
import requests
def send_request():
    # ここを切り替えていく
    url = 'http://localhost:5000/'
    # url = 'http://127.0.0.1:5000/'
    # url = 'http://172.30.44.147:5000/'
    try:
        response = requests.get(url)
        if response.status_code == 200:
            print('Response from server:', response.text)
        else:
            print('Failed to get a valid response. Status code:', response.status_code)
    except requests.exceptions.RequestException as e:
        print('An error occurred:', e)
if __name__ == '__main__':
    send_request()

Flaskの実行について

実行時に0.0.0.0を指定するとローカルホスト(127.0.0.1)とWSL内のIPで起動されるためどちらのIPでも接続が可能となる。

image.png
image.png

127.0.0.1の場合はローカルホストのみ
image.png

それに対してWSL2のIPを指定してもエラーとなる
image.png

WSL2のIP

以下のコマンドで表示される

ip addr show eth0 | grep inet

>> inet 172.30.44.147/20 brd 172.30.47.255 scope global eth0

Windowsの仮想ネットワークと同一のLANの中にいるため接続ができる

ipconfig

イーサネット アダプター vEthernet (WSL (Hyper-V firewall)):

   接続固有の DNS サフィックス . . . . .:
   IPv4 アドレス . . . . . . . . . . . .: 172.30.32.1
   サブネット マスク . . . . . . . . . .: 255.255.240.0
   デフォルト ゲートウェイ . . . . . . .:

まとめ

設定ファイルやポートフォワードを意識しなくても基本的に問題がないことが分かった。

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?