forked from influxdata/influxdb-python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmisc.py
46 lines (40 loc) · 1.36 KB
/
misc.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import socket
def get_free_ports(num_ports, ip='127.0.0.1'):
"""Get `num_ports` free/available ports on the interface linked to the `ip´
:param int num_ports: The number of free ports to get
:param str ip: The ip on which the ports have to be taken
:return: a set of ports number
"""
sock_ports = []
ports = set()
try:
for _ in range(num_ports):
sock = socket.socket()
cur = [sock, -1]
# append the socket directly,
# so that it'll be also closed (no leaked resource)
# in the finally here after.
sock_ports.append(cur)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((ip, 0))
cur[1] = sock.getsockname()[1]
finally:
for sock, port in sock_ports:
sock.close()
ports.add(port)
assert num_ports == len(ports)
return ports
def is_port_open(port, ip='127.0.0.1'):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
result = sock.connect_ex((ip, port))
if not result:
sock.shutdown(socket.SHUT_RDWR)
return result == 0
finally:
sock.close()