|
1 | 1 | import fnmatch |
2 | 2 | import json |
| 3 | +import socket |
3 | 4 | import urllib.parse |
4 | 5 | from collections import defaultdict |
5 | 6 | from collections import namedtuple |
6 | 7 | from collections.abc import Mapping, Sequence |
| 8 | +from functools import lru_cache |
7 | 9 | from functools import partial |
8 | 10 | from os import path, environ |
9 | 11 |
|
10 | 12 | from tornado import template |
11 | | -from functools import lru_cache |
12 | 13 |
|
13 | 14 | from ..__version__ import __version__ as version |
14 | 15 | from ..exceptions import PyWebIOWarning |
@@ -275,6 +276,48 @@ def deserialize_binary_event(data: bytes): |
275 | 276 | return event |
276 | 277 |
|
277 | 278 |
|
| 279 | +def get_interface_ip(family: socket.AddressFamily) -> str: |
| 280 | + """Get the IP address of an external interface. Used when binding to |
| 281 | + 0.0.0.0 or :: to show a more useful URL. |
| 282 | +
|
| 283 | + Copy from https://github.com/pallets/werkzeug/blob/df7492ab66aaced5eea964a58309caaadb1e8903/src/werkzeug/serving.py |
| 284 | + Under BSD-3-Clause License |
| 285 | + """ |
| 286 | + # arbitrary private address |
| 287 | + host = "fd31:f903:5ab5:1::1" if family == socket.AF_INET6 else "10.253.155.219" |
| 288 | + |
| 289 | + with socket.socket(family, socket.SOCK_DGRAM) as s: |
| 290 | + try: |
| 291 | + s.connect((host, 58162)) |
| 292 | + except OSError: |
| 293 | + return "::1" if family == socket.AF_INET6 else "127.0.0.1" |
| 294 | + |
| 295 | + return s.getsockname()[0] # type: ignore |
| 296 | + |
| 297 | + |
| 298 | +def print_listen_address(host, port): |
| 299 | + if not host: |
| 300 | + host = '0.0.0.0' |
| 301 | + |
| 302 | + all_address = False |
| 303 | + if host == "0.0.0.0": |
| 304 | + all_address = True |
| 305 | + host = get_interface_ip(socket.AF_INET) |
| 306 | + elif host == "::": |
| 307 | + all_address = True |
| 308 | + host = get_interface_ip(socket.AF_INET6) |
| 309 | + |
| 310 | + if ':' in host: # ipv6 |
| 311 | + host = '[%s]' % host |
| 312 | + |
| 313 | + if all_address: |
| 314 | + print('Running on all addresses.') |
| 315 | + print('Use http://%s:%s/ to access the application' % (host, port)) |
| 316 | + else: |
| 317 | + print('Running on http://%s:%s/' % (host, port)) |
| 318 | + |
| 319 | + |
| 320 | + |
278 | 321 | def seo(title, description=None, app=None): |
279 | 322 | """Set the SEO information of the PyWebIO application (web page information provided when indexed by search engines) |
280 | 323 |
|
|
0 commit comments