Return Value of Socket Accept in Python

For a server managing multiple connections, you can log and track client details using accept(). This enhances monitoring and debugging during runtime.

Here’s how you can implement it:

import socket

# Server setup
s = socket.socket()
host = socket.gethostname()
port = 1234
s.bind((host, port))

s.listen(5)

client_info = []  # Store connected clients

while True:
    c, addr = s.accept()  # Accept connection
    client_info.append(addr)  # Log client details
    print(f"Client connected from IP: {addr[0]} on Port: {addr[1]}")
    c.send(b'Thank you for connecting')
    c.close()

    # Display all connected clients
    print("Connected Clients:", client_info)

Key Details:

  1. Client Details: The addr tuple returned by accept() contains the client’s IP and port, which is stored in client_info for future reference.
  2. Connection Tracking: The server logs and prints all client details each time a new connection is established.

Example Output:

Client connected from IP: 192.168.0.99 on Port: 49170
Connected Clients: [('192.168.0.99', 49170)]

Client connected from IP: 192.168.0.99 on Port: 49171
Connected Clients: [('192.168.0.99', 49170), ('192.168.0.99', 49171)]

This approach is particularly useful for debugging or building robust servers that manage multiple client connections efficiently. It ensures you have a clear log of all active and past connections during the server’s runtime.