Skip to content

Commit

Permalink
[전희선] 10주차 미션 제출 (#96)
Browse files Browse the repository at this point in the history
  • Loading branch information
heehehe authored Jul 6, 2024
1 parent c038c61 commit 79ac359
Showing 1 changed file with 44 additions and 0 deletions.
44 changes: 44 additions & 0 deletions 8th_members/전희선/10주차.md
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">

0 comments on commit 79ac359

Please sign in to comment.