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 multithreaded TCP server.
Crank out the following code:
1 import socket
2 import threading
3 IP = '0.0.0.0'
4 PORT = 8080
5 def main():
6 server =
socket.socket(socket.AF_INET,socket.SOCK_STREAM)
7 server.bind((IP, PORT)) 1
8 server.listen(5) 2
9 print(f'[*] Listening on {IP}:{PORT}')
10 while True:
11 client, address = server.accept() 3
12 print(f'[*] Accepted connection from
{address[0]}:
13 {address[1]}')
14 client_handler =
threading.Thread(target=handle_client, args=
(client,))
15 client_handler.start() 4
16 def handle_client(client_socket):
17 5 with client_socket as sock:
18 request = sock.recv(1024)
19 print(f'[*] Received: {request.decode("utf-
8")}')
20 sock.send(b'ACK')
21 if __name__ == '__main__':
22 main()
23
24
To start off, we pass in the IP address and
port we want the server to listen on 1. Next,
we tell the server to start listening 2, with a
maximum backlog of connections set to 5. We
then put the server into its main loop, where
it waits for an incoming connection. When a
client connects 3, we receive the client socket
in the client variable and the remote
connection details in the address 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 4, at which point the main server
loop is ready to handle another incoming
connection. The handle_client function 5
performs the recv() and then sends a simple
message back to the client.
If you use the TCP client that we built
earlier, you can send some test packets to the
server. You should see output like the
following:
[*] Listening on 0.0.0.0:9998 [*] Accepted
connection from: 127.0.0.1:62512 [*] Received:
ABCDEF That’s it! While pretty simple, this is
a very useful piece of code.
We’ll extend it in the next couple of sections,
when we build a netcat replacement and a TCP
proxy.