##// END OF EJS Templates
utils: by default use OS implemented pick port which is WAAAY faster, leave fallback if we need specific range.
super-admin -
r4883:58394708 default
parent child Browse files
Show More
@@ -39,6 +39,7 b' import socket'
39 import errno
39 import errno
40 import random
40 import random
41 from functools import update_wrapper, partial, wraps
41 from functools import update_wrapper, partial, wraps
42 from contextlib import closing
42
43
43 import pygments.lexers
44 import pygments.lexers
44 import sqlalchemy
45 import sqlalchemy
@@ -1190,23 +1191,21 b' def user_agent_normalizer(user_agent_raw'
1190 return ua
1191 return ua
1191
1192
1192
1193
1193 def get_available_port(min_port=40000, max_port=55555):
1194 def get_available_port(min_port=40000, max_port=55555, use_range=False):
1194 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
1195 hostname = ''
1195 hostname = '127.0.0.1'
1196 pick_port = min_port
1197
1198 for _ in range(min_port, max_port):
1196 for _ in range(min_port, max_port):
1199 pick_port = random.randint(min_port, max_port)
1197 pick_port = 0
1200 try:
1198 if use_range:
1201 sock.bind((hostname, pick_port))
1199 pick_port = random.randint(min_port, max_port)
1202 sock.close()
1200
1203 break
1201 with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s:
1204 except OSError:
1202 try:
1205 continue
1203 s.bind((hostname, pick_port))
1206 except socket.error as e:
1204 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1207 if e.args[0] in [errno.EADDRINUSE, errno.ECONNREFUSED]:
1205 return s.getsockname()[1]
1206 except OSError:
1208 continue
1207 continue
1209 raise
1208 except socket.error as e:
1210
1209 if e.args[0] in [errno.EADDRINUSE, errno.ECONNREFUSED]:
1211 del sock
1210 continue
1212 return pick_port
1211 raise
General Comments 0
You need to be logged in to leave comments. Login now