How To Create TCP Server For Hacking With Python
Need Of Creating A TCP Server For Hacking
TCP/IP is currently the most common standard for communicating devices within computer networks. The TCP/IP stack is divided into several layers, each of which is important for particular aspects of communication. It is possible to develop each of these layers without affecting adjacent ones.
How To Create A TCP Server With Python
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 craft-
ing 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))
To start off, we pass in the IP address and port we want the server to
server.listen(5) print "[*] Listening on %s:%d" % (bind_ip,bind_port)
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.
# this is our client-handling thread w def handle_client(client_socket): # print out what the client sends request = client_socket.recv(1024) print "[*] Received: %s" % request # send back a packet client_socket.send("ACK!") client_socket.close()
The handle_client w function performs the recv() and then sends a simple
message back to the client.
while True: client,addr = server.accept() print "[*] Accepted connection from: %s:%d" % (addr,addr) # spin up our client thread to handle incoming data client_handler = threading.Thread(target=handle_client,args=(client,)) client_handler.start()
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.
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: Hello
That’s it! Pretty simple, but this is a very useful piece of code which we
will extend in the next couple of sections when we build a netcat replace-
ment and a TCP proxy.
Also Check Creating A TCP Client for Hacking Using Python | For Hackers
2 thoughts on “How To Create TCP Server For Hacking With Python”