-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver_client.py
More file actions
55 lines (40 loc) · 1.3 KB
/
server_client.py
File metadata and controls
55 lines (40 loc) · 1.3 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
import socket
PORT = 2222
BUFFER_SIZE = 1024
MAX_CONNECTIONS = 100
def main():
# Create server socket
server_fd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Set socket options to reuse address
server_fd.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# Set up server address
server_addr = ('0.0.0.0', PORT)
# Bind socket
try:
server_fd.bind(server_addr)
except OSError as e:
print(f"Bind failed: {e}")
server_fd.close()
return
# Listen for connections
try:
server_fd.listen(MAX_CONNECTIONS)
except OSError as e:
print(f"Listen failed: {e}")
server_fd.close()
return
print(f"Server listening on port {PORT}...")
# Lists to store client IPs
try:
while True:
try:
# Accept client connection
client_fd, client_addr = server_fd.accept()
client_ip = client_addr[0]
client_fd.send(f"{client_ip}\n".encode('utf-8'))
except OSError as e:
print(f"Receive or send failed for {client_ip}: {e}")
except OSError as e:
print(f"Accept failed: {e}")
if __name__ == "__main__":
main()