-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimpleserver.py
More file actions
62 lines (49 loc) · 1.45 KB
/
simpleserver.py
File metadata and controls
62 lines (49 loc) · 1.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#!/usr/bin/env python3
"""Server
Creates a TCP server on a given port
Usage: $ python3 simpleserver.py <port>
"""
import signal
import socket
import sys
from types import FrameType
from typing import Optional
sock = None
def handler(signum: int, frame: Optional[FrameType]) -> None:
"""Handles interrupt and prompts if program should be ended
Args:
signmum (int): Type of interrupt
frame (FrameType): Source of interrupt
"""
reply = input("trl-c was pressed. Exit? y/n ")
if reply == "y":
sock.close()
sys.exit(1)
def server(port: str) -> None:
"""Starts a simple server on given port
Args:
port (str): The port of the server
"""
try:
global sock
port = int(port)
host = socket.gethostname()
# Socket that is IPv4 and TCP
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((host, port))
sock.listen(1)
print("[+] Server started")
while 1:
conn, addr = sock.accept()
print(f"[+] Connected to {addr}")
msg = f"Received connection from {addr}"
conn.send(msg.encode("ascii"))
except Exception as e:
print(f"[-] Server failed: {e}")
sys.exit(1)
if __name__ == "__main__":
if len(sys.argv) < 2:
print(f"[!] Usage: python3 {sys.argv[0]} <port>")
sys.exit(1)
signal.signal(signal.SIGINT, handler)
server(sys.argv[1])