TCP Server
Creating TCP servers in Python is just as easy as creating a client. 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. Crank out the code below:
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 client variable, and the remote connection details into the addr variable.
- We then create a new thread object that points to our handle_client function, 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_client function performs the recv() and then sends a simple message back to the 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())
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.
Top comments (0)