comparison planemo/lib/python3.7/site-packages/galaxy/util/sockets.py @ 1:56ad4e20f292 draft

"planemo upload commit 6eee67778febed82ddd413c3ca40b3183a3898f1"
author guerler
date Fri, 31 Jul 2020 00:32:28 -0400
parents
children
comparison
equal deleted inserted replaced
0:d30785e31577 1:56ad4e20f292
1 import random
2 import socket
3
4 from galaxy.util import commands
5
6
7 def get_ip():
8 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
9 try:
10 # doesn't even have to be reachable
11 s.connect(('10.255.255.255', 1))
12 ip = s.getsockname()[0]
13 except Exception:
14 ip = None
15 finally:
16 s.close()
17 return ip
18
19
20 def unused_port(range=None):
21 if range:
22 return __unused_port_on_range(range)
23 else:
24 return __unused_port_rangeless()
25
26
27 def __unused_port_rangeless():
28 # TODO: Allow ranges (though then need to guess and check)...
29 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
30 s.bind(('localhost', 0))
31 addr, port = s.getsockname()
32 s.close()
33 return port
34
35
36 def __unused_port_on_range(range):
37 assert range[0] and range[1]
38
39 # Find all ports that are already occupied
40 cmd_netstat = ["netstat", "tuln"]
41 stdout = commands.execute(cmd_netstat)
42
43 occupied_ports = set()
44 for line in stdout.split('\n'):
45 if line.startswith('tcp') or line.startswith('tcp6'):
46 col = line.split()
47 local_address = col[3]
48 local_port = local_address.split(':')[1]
49 occupied_ports.add(int(local_port))
50
51 # Generate random free port number.
52 while True:
53 port = random.randrange(range[0], range[1])
54 if port not in occupied_ports:
55 break
56 return port