Ensure that we can bind and connect to localhost

otherwise fallback to 127.0.0.1 for defaults
This commit is contained in:
Min RK
2015-12-15 13:37:30 +01:00
parent aa529f3aba
commit 4785a1ef87
5 changed files with 47 additions and 11 deletions

View File

@@ -6,10 +6,12 @@
from binascii import b2a_hex
import errno
import hashlib
from hmac import compare_digest
import os
import socket
from threading import Thread
import uuid
from hmac import compare_digest
import warnings
from tornado import web, gen, ioloop
from tornado.httpclient import AsyncHTTPClient, HTTPError
@@ -192,3 +194,36 @@ def url_path_join(*pieces):
result = '/'
return result
def localhost():
"""Return localhost or 127.0.0.1"""
if hasattr(localhost, '_localhost'):
return localhost._localhost
binder = connector = None
try:
binder = socket.socket()
binder.bind(('localhost', 0))
binder.listen(1)
port = binder.getsockname()[1]
def accept():
try:
conn, addr = binder.accept()
except ConnectionAbortedError:
pass
else:
conn.close()
t = Thread(target=accept)
t.start()
connector = socket.create_connection(('localhost', port), timeout=10)
t.join(timeout=10)
except (socket.error, socket.gaierror) as e:
warnings.warn("localhost doesn't appear to work, using 127.0.0.1\n%s" % e, RuntimeWarning)
localhost._localhost = '127.0.0.1'
else:
localhost._localhost = 'localhost'
finally:
if binder:
binder.close()
if connector:
connector.close()
return localhost._localhost