Simple TCP client and server using python
Introduction
There are powerful libraries and tools written in python. In the core part of these libraries and tools is the socket module. This module provides access to the BSD socket interface and avaliable on numerous platforms, Unix, Window, and Mac OS X etc. Here, I'm going to create a TCP client and TCP server to test and transfer data.
TCP client
Using a TCP client, we could test service, transfer trash data, do fuzzy tests, and execute any kinds of works. First, we use AF_INET address family, where host is representing either a hostname in Internet domain notation like 'en.wikipedia.org' or an IPv4 address like '198.35.26.96', and SOCK_STREAM which means TCP client.
Here are a few assumptions in the below code:
Here are a few assumptions in the below code:
- Connection would be successful.
- Server would wait for client to send data first.
- Server would response in a short time.
1
2
3
4
5
6
7
8
9
10
11
12
import socket
target_host = "0.0.0.0"
target_port = 27700
# create a socket connection
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# let the client connect
client.connect((target_host, target_port))
# send some data
client.send("SYN")
# get some data
response = client.recv(4096)
print response
TCP server
To establish a TCP server, we would build a multi-threaded TCP server. After binding the listening host ip and port, specify the maximum number value of the connections made to the socket.
Everytime the server accept a connection, store the socket object into client variable and create a new thread to handle this connection using the handle_client function.
Everytime the server accept a connection, store the socket object into client variable and create a new thread to handle this connection using the handle_client function.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import socket
import threading
bind_ip = "0.0.0.0"
bind_port = 27700
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((bind_ip, bind_port))
server.listen(5)
print "[*] Listening on %s:%d" % (bind_ip, bind_port)
# This is the thread we handle the data from the client
def handle_client(client_socket):
# show the data from the client
request = client_socket.recv(1024)
print "[*] Received: %s" % request
# Return a packet
client_socket.send("ACK!")
client_socket.close()
while True:
client, addr = server.accept()
print "[*] Accepted connection from: %s:%d" % (addr[0], addr[1])
# activate the function to handle the data from client
client_handler = threading.Thread(target = handle_client, args=(client,))
client_handler.start()
Demonstration
Execute the server and then execute the client in another terminal window. This is the output in the server window.
This is the output in the output in the client window.
Conclusion
It's quite easy but powerful to write these TCP connections in Python. Afterward, there would be more extension of these applications.