forked from p15670423/monkey
Agent: Use set in get_free_tcp_port()
This commit is contained in:
parent
33da121465
commit
0398b31ece
|
@ -1,6 +1,5 @@
|
|||
import queue
|
||||
from bisect import bisect_left
|
||||
from typing import Any, Dict, List, MutableMapping, Sequence, Type, TypeVar
|
||||
from typing import Any, Dict, List, MutableMapping, Type, TypeVar
|
||||
|
||||
T = TypeVar("T")
|
||||
|
||||
|
@ -49,15 +48,3 @@ def del_key(mapping: MutableMapping[T, Any], key: T):
|
|||
del mapping[key]
|
||||
except KeyError:
|
||||
pass
|
||||
|
||||
|
||||
def in_sorted_sequence(item: Any, seq: Sequence[Any]) -> bool:
|
||||
"""
|
||||
Provides fast search in the case that the sequence is sorted.
|
||||
|
||||
:param item: The item to search in the list.
|
||||
:param seq: The sorted sequence in which to search the item.
|
||||
:return: True if the item was found in the list, otherwise false.
|
||||
"""
|
||||
i = bisect_left(seq, item)
|
||||
return i != len(seq) and seq[i] == item
|
||||
|
|
|
@ -9,7 +9,6 @@ from typing import List
|
|||
import netifaces
|
||||
import psutil
|
||||
|
||||
from common.utils.code_utils import in_sorted_sequence
|
||||
from infection_monkey.utils.environment import is_windows_os
|
||||
|
||||
from .ports import COMMON_PORTS
|
||||
|
@ -123,10 +122,10 @@ else:
|
|||
|
||||
def get_free_tcp_port(min_range=1024, max_range=65535):
|
||||
|
||||
in_use = sorted([conn.laddr[1] for conn in psutil.net_connections()])
|
||||
in_use = {conn.laddr[1] for conn in psutil.net_connections()}
|
||||
|
||||
for port in COMMON_PORTS:
|
||||
if not in_sorted_sequence(port, in_use):
|
||||
if port not in in_use:
|
||||
return port
|
||||
|
||||
min_range = max(1, min_range)
|
||||
|
@ -134,7 +133,7 @@ def get_free_tcp_port(min_range=1024, max_range=65535):
|
|||
ports = list(range(min_range, max_range))
|
||||
shuffle(ports)
|
||||
for port in ports:
|
||||
if not in_sorted_sequence(port, in_use):
|
||||
if port not in in_use:
|
||||
return port
|
||||
|
||||
return None
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
from queue import Queue
|
||||
|
||||
from common.utils.code_utils import del_key, in_sorted_sequence, queue_to_list
|
||||
from common.utils.code_utils import del_key, queue_to_list
|
||||
|
||||
|
||||
def test_empty_queue_to_empty_list():
|
||||
|
@ -40,11 +40,3 @@ def test_del_key__nonexistant_key():
|
|||
|
||||
# This test passes if the following call does not raise an error
|
||||
del_key(my_dict, key_to_delete)
|
||||
|
||||
|
||||
def test_in_sorted_sequence__finds_item():
|
||||
assert in_sorted_sequence(99, range(100))
|
||||
|
||||
|
||||
def test_in_sorted_sequence__does_not_find_nonexistent_item():
|
||||
assert not in_sorted_sequence(101, range(100))
|
||||
|
|
Loading…
Reference in New Issue