generated from Pseudo-Lab/Jupyter-Book-Template
-
Notifications
You must be signed in to change notification settings - Fork 18
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
44 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
### 멀티스레딩 + 스레드 개수 제한 통한 port scanner 실행 | ||
|
||
- 실행 코드 | ||
```python | ||
import socket | ||
import time | ||
from concurrent.futures import ThreadPoolExecutor, as_completed | ||
from queue import Queue | ||
import sys | ||
|
||
timeout = 1.0 | ||
|
||
def check_port(host: str, port: int) -> int: | ||
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: | ||
sock.settimeout(timeout) | ||
result = sock.connect_ex((host, port)) | ||
if result == 0: | ||
return port | ||
return None | ||
|
||
def main(): | ||
MAX_WORKERS = int(sys.argv[1]) # worker 수 입력으로 받아 다르게 테스트 | ||
|
||
start = time.time() | ||
host = "localhost" # Replace with a host you own | ||
open_ports = [] | ||
|
||
with ThreadPoolExecutor(max_workers=MAX_WORKERS) as executor: | ||
futures = [executor.submit(check_port, host, port) for port in range(10000, 65536)] # port 범위 확장 | ||
|
||
for future in as_completed(futures): | ||
port = future.result() | ||
if port is not None: | ||
open_ports.append(port) | ||
|
||
for port in open_ports: | ||
print(f"Port {port} is open") | ||
print(f"Completed scan in {time.time() - start:.2f} seconds") | ||
|
||
if __name__ == '__main__': | ||
main() | ||
``` | ||
- 결과: worker 수를 30으로 했을 때 가장 적게 걸리는 점을 통해, 멀티스레딩도 오버헤드가 존재하며 (멀티프로세스에 비해 상대적으로 적을 뿐) worker 개수가 많다고 항상 좋은 것은 아니라는 점을 확인할 수 있었습니다 :) | ||
<img width="553" alt="image" src="https://github.com/heehehe/CPython-Guide/assets/41580746/ac04e28c-e075-42db-acf8-593efdcc3b3f"> |