Simple TCP Server in Python
TCP Server
TCP servers in Python are just as easy to create as clients. You might want to use your own TCP server when writing command shells or crafting a proxy (both of which we'll do later). Let's start by creating a standard multi-threaded TCP server.
import socket
import threading
bind_ip = "0.0.0.0"
bind_port = 9999
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((bind_ip, bind_port))
server.listen(5)
print(f"[*] Listening on {bind_ip}:{bind_port}")
def handle_client(client_socket):
request = client_socket.recv(1024)
print(f"[*] Received: {request.decode()}")
client_socket.send(b"ACK!")
client_socket.close()
while True:
client, addr = server.accept()
print(f"[*] Accepted connection from: {addr[0]}:{addr[1]}")
client_handler = threading.Thread(target=handle_client, args=(client,))
client_handler.start()
- To start off, we pass in the IP address and port we want the server to listen on.
- Next we tell the server to start listening with a maximum backlog of connections set to 5.
- We then put the server into its main loop, where it is waiting for an incoming connection.
- When a client connects, we receive the client socket into the
clientvariable, and the remote connection details into theaddrvariable. - We then create a new thread object that points to our
handle_clientfunction, and we pass it the client socket object as an argument. - We then start the thread to handle the client connection, and our main server loop is ready to handle another incoming connection.
- The
handle_clientfunction performs therecv()and then sends a simple message back to the client.
Client
import socket
target_host = "127.0.01"
target_port = 9999
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((target_host, target_port))
client.send(b"AAABBBCCC")
response = client.recv(4096)
print(response.decode())
Output
If you use the TCP client that we built earlier, you can send some test packets to the server and you should see output like the following:
[*] Listening on 0.0.0.0:9999
[*] Accepted connection from: 127.0.0.1:62512
[*] Received: ABCDE
That's it! Pretty simple.
Comments
No comments yet. Start the discussion.