Skip to content

Commit 79ac359

Browse files
authored
[전희선] 10주차 미션 제출 (#96)
1 parent c038c61 commit 79ac359

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

8th_members/전희선/10주차.md

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
### 멀티스레딩 + 스레드 개수 제한 통한 port scanner 실행
2+
3+
- 실행 코드
4+
```python
5+
import socket
6+
import time
7+
from concurrent.futures import ThreadPoolExecutor, as_completed
8+
from queue import Queue
9+
import sys
10+
11+
timeout = 1.0
12+
13+
def check_port(host: str, port: int) -> int:
14+
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
15+
sock.settimeout(timeout)
16+
result = sock.connect_ex((host, port))
17+
if result == 0:
18+
return port
19+
return None
20+
21+
def main():
22+
MAX_WORKERS = int(sys.argv[1]) # worker 수 입력으로 받아 다르게 테스트
23+
24+
start = time.time()
25+
host = "localhost" # Replace with a host you own
26+
open_ports = []
27+
28+
with ThreadPoolExecutor(max_workers=MAX_WORKERS) as executor:
29+
futures = [executor.submit(check_port, host, port) for port in range(10000, 65536)] # port 범위 확장
30+
31+
for future in as_completed(futures):
32+
port = future.result()
33+
if port is not None:
34+
open_ports.append(port)
35+
36+
for port in open_ports:
37+
print(f"Port {port} is open")
38+
print(f"Completed scan in {time.time() - start:.2f} seconds")
39+
40+
if __name__ == '__main__':
41+
main()
42+
```
43+
- 결과: worker 수를 30으로 했을 때 가장 적게 걸리는 점을 통해, 멀티스레딩도 오버헤드가 존재하며 (멀티프로세스에 비해 상대적으로 적을 뿐) worker 개수가 많다고 항상 좋은 것은 아니라는 점을 확인할 수 있었습니다 :)
44+
<img width="553" alt="image" src="https://github.com/heehehe/CPython-Guide/assets/41580746/ac04e28c-e075-42db-acf8-593efdcc3b3f">

0 commit comments

Comments
 (0)