|
10 | 10 | import logging
|
11 | 11 | import typing
|
12 | 12 | import copy
|
| 13 | +import socket |
13 | 14 |
|
14 | 15 | from ..exceptions import ExecUtilException
|
15 | 16 | from ..exceptions import InvalidOperationException
|
@@ -681,22 +682,31 @@ def get_process_children(self, pid):
|
681 | 682 | def is_port_free(self, number: int) -> bool:
|
682 | 683 | assert type(number) == int # noqa: E721
|
683 | 684 |
|
684 |
| - cmd = ["nc", "-w", "5", "-z", "-v", "localhost", str(number)] |
| 685 | + # grep -q returns 0 if a listening socket on that port is found |
| 686 | + port_hex = format(number, '04X') |
685 | 687 |
|
686 |
| - exit_status, output, error = self.exec_command(cmd=cmd, encoding=get_default_encoding(), ignore_errors=True, verbose=True) |
| 688 | + # Search /proc/net/tcp and tcp6 for any entry with this port |
| 689 | + cmd = ['/bin/bash', '-lc', |
| 690 | + f"grep -q ':{port_hex} ' /proc/net/tcp /proc/net/tcp6"] |
687 | 691 |
|
688 |
| - assert type(output) == str # noqa: E721 |
689 |
| - assert type(error) == str # noqa: E721 |
| 692 | + exit_status, output, error = self.exec_command( |
| 693 | + cmd=cmd, |
| 694 | + encoding=get_default_encoding(), |
| 695 | + ignore_errors=True, |
| 696 | + verbose=True |
| 697 | + ) |
690 | 698 |
|
| 699 | + # grep exit 0 -> port is busy |
691 | 700 | if exit_status == 0:
|
692 |
| - return __class__._is_port_free__process_0(error) |
| 701 | + return False |
693 | 702 |
|
| 703 | + # grep exit 1 -> port is free |
694 | 704 | if exit_status == 1:
|
695 |
| - return __class__._is_port_free__process_1(error) |
696 |
| - |
697 |
| - errMsg = "nc returns an unknown result code: {0}".format(exit_status) |
| 705 | + return True |
698 | 706 |
|
699 |
| - RaiseError.CommandExecutionError( |
| 707 | + # any other code is an unexpected error |
| 708 | + errMsg = f"grep returned unexpected exit code: {exit_status}" |
| 709 | + raise RaiseError.CommandExecutionError( |
700 | 710 | cmd=cmd,
|
701 | 711 | exit_code=exit_status,
|
702 | 712 | message=errMsg,
|
@@ -746,12 +756,7 @@ def _is_port_free__process_0(error: str) -> bool:
|
746 | 756 | @staticmethod
|
747 | 757 | def _is_port_free__process_1(error: str) -> bool:
|
748 | 758 | assert type(error) == str # noqa: E721
|
749 |
| - # |
750 |
| - # Example of error text: |
751 |
| - # "nc: connect to localhost (127.0.0.1) port 1024 (tcp) failed: Connection refused\n" |
752 |
| - # |
753 | 759 | # May be here is needed to check error message?
|
754 |
| - # |
755 | 760 | return True
|
756 | 761 |
|
757 | 762 | @staticmethod
|
|
0 commit comments