T
T
TODO•SEC
Search…
TcpServer.py
TCP Server script from Python section of PTSv4 (eLearnSecurity)
1
# Goal
2
# Bind to specific IPv4 address and TCP port (client) and
3
# listen for incoming TCP communications (server)
4
5
# import socket module (low level network interface)
6
7
import socket
8
9
# Takes input from the user and saves it in variables SRV_ADDR and SRV_PORT
10
11
SRV_ADDR = input("Type the server IP address: ")
12
SRV_PORT = int(input("Type the server port: "))
13
14
# Create a new socket using the default family socket (AF_INET) that uses TCP and
15
# the default socket type connection-oriented (SOCK_STREAM)
16
17
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
18
19
# bind function binds the socket to the provided address and port, while
20
# the listen function instructs the socket to listen for an incoming connection.
21
22
s.bind((SRV_ADDR, SRV_PORT))
23
24
# the argument 1 specifies the maximum number of queued connections.
25
26
s.listen(1)
27
print("Server started! Waiting for connections...")
28
29
# connection is the socket object we will use to send and receive data
30
# address contains the client address bound to the socket
31
connection, address = s.accept()
32
33
# Print address of connected client and
34
35
print('Client connected with address:', address)
36
37
# start an infinite loop
38
39
while 1:
40
data = connection.recv(1024)
41
if not data: break
42
connection.sendall(b'-- Message Received --\n')
43
44
# print all messages received from it
45
46
print(data.decode('utf-8'))
47
connection.close()
Copied!
Last modified 8d ago
Copy link