This is a guide to write a quick simple TCP client in pure python.
First of all, why would anyone need this ?
Industry Servers dosent have tools like curl or wget, and most of the time have restricted network access, so downloading using the package manager isn't possible too.
But most if not all of the time, you can find a version of python installed.
So we will try to make a TCP client without any additional libraries, just using the buit in Sockets Library
import socket
target_host = "www.google.com"
target_port = 80
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((target_host, target_port))
client.send(b"GET / HTTP/1.1\r\nHost: google.com\r\n\r\n")
response = client.recv(4096)
print(response.decode())
We first create a socket object with the AF_INET and SOCK_STREAM parameters.
- The
AF_INETparameter is saying we are going to use a standard IPv4 address or hostname, andSOCK_STREAMindicates that this will be a TCP client. - We then connect the client to the server and send it some data.
- The last step is to receive some data back and print out the response.
- This is the simplest form of a TCP client, but the one you will write most often.
In the above code snippet, we are making some serious assumptions about sockets that you definitely want to be aware of. The first assumption is that our connection will always succeed, and the second is that the server is always expecting us to send data first (as opposed to servers that expect to send data to you first and await your response). Our third assumption is that the server will always send us data back in a timely fashion. We make these assumptions largely for simplicity’s sake. While programmers have varied opinions about how to deal with blocking sockets, exception-handling in sockets, and the like, it’s quite rare for pentesters to build these niceties into the quick-and-dirty tools for recon or exploitation work, so we’ll omit them.
Top comments (0)