meerschaum.utils.networking

Utility functions pertaining to network functionality (e.g. available ports).

 1#! /usr/bin/env python3
 2# -*- coding: utf-8 -*-
 3# vim:fenc=utf-8
 4
 5"""
 6Utility functions pertaining to network functionality (e.g. available ports).
 7"""
 8
 9def is_port_in_use(port: int):
10    """Try to bind to a port and return whether it is available.
11
12    Parameters
13    ----------
14    port: int :
15        
16
17    Returns
18    -------
19
20    """
21    import socket
22    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
23        return s.connect_ex(('localhost', port)) == 0
24
25
26def find_open_ports(start_port: int = 8000, end_port: int = 9001):
27    """Check a range of ports and yield open ports.
28    
29    Found from StackExchange here:
30    https://codereview.stackexchange.com/questions/116450/find-available-ports-on-localhost
31
32    Parameters
33    ----------
34    start_port: int :
35         (Default value = 8000)
36    end_port: int :
37         (Default value = 9001)
38
39    Returns
40    -------
41
42    """
43    for port in range(start_port, end_port):
44        if not is_port_in_use(port):
45            yield port
def is_port_in_use(port: int):
10def is_port_in_use(port: int):
11    """Try to bind to a port and return whether it is available.
12
13    Parameters
14    ----------
15    port: int :
16        
17
18    Returns
19    -------
20
21    """
22    import socket
23    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
24        return s.connect_ex(('localhost', port)) == 0

Try to bind to a port and return whether it is available.

Parameters
  • port (int :):

  • Returns

  • -------
def find_open_ports(start_port: int = 8000, end_port: int = 9001):
27def find_open_ports(start_port: int = 8000, end_port: int = 9001):
28    """Check a range of ports and yield open ports.
29    
30    Found from StackExchange here:
31    https://codereview.stackexchange.com/questions/116450/find-available-ports-on-localhost
32
33    Parameters
34    ----------
35    start_port: int :
36         (Default value = 8000)
37    end_port: int :
38         (Default value = 9001)
39
40    Returns
41    -------
42
43    """
44    for port in range(start_port, end_port):
45        if not is_port_in_use(port):
46            yield port

Check a range of ports and yield open ports.

Found from StackExchange here: https://codereview.stackexchange.com/questions/116450/find-available-ports-on-localhost

Parameters
  • start_port (int :): (Default value = 8000)
  • end_port (int :): (Default value = 9001)
  • Returns
  • -------