-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTCP-Client.py
45 lines (36 loc) · 1.22 KB
/
TCP-Client.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#!/usr/bin/python3
import argparse
import socket
# Create a command-line argument parser
parser = argparse.ArgumentParser(description="Connect to a server on a specified IP address and port")
parser.add_argument("--ip", type=str, required=True, help="the IP address of the server to connect to")
parser.add_argument("--port", type=int, required=True, help="the port number to connect to")
# Parse the command-line arguments
args = parser.parse_args()
# Create a new socket object
try:
clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error as e:
print("Error creating socket: %s" % e)
exit()
# Set the IP address and port number
ip_address = args.ip
port = args.port
# Connect to the server
try:
clientsocket.connect((ip_address, port))
print("Connected to server at %s:%s" % (ip_address, port))
except socket.error as e:
print("Error connecting to server: %s" % e)
exit()
# Receive data from the server
try:
message = clientsocket.recv(1024)
except socket.error as e:
print("Error receiving data from server: %s" % e)
clientsocket.close()
exit()
# Close the connection
clientsocket.close()
# Print the message received from the server
print(message.decode('ascii'))