-
Notifications
You must be signed in to change notification settings - Fork 1
/
udp_client.py
52 lines (40 loc) · 1.53 KB
/
udp_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
46
47
48
49
50
51
import socket
import sys
def udp_client(input_file, output_file, ip, port, timeout=5):
try:
# Create a UDP socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
client_socket.settimeout(timeout)
# Read the input file
with open(input_file, "rb") as f:
data = f.read()
# Send the data to the server
client_socket.sendto(data, (ip, port))
print(f"Sent data from {input_file} to {ip}:{port}")
# Wait for the response
try:
response, server = client_socket.recvfrom(4096) # Buffer size of 4096 bytes
print(f"Received response from {server}")
# Write the response to the output file
with open(output_file, "wb") as f:
f.write(response)
print(f"Response written to {output_file}")
except socket.timeout:
print("No response received: timeout occurred.")
except FileNotFoundError:
print(f"Error: File {input_file} not found.")
except Exception as e:
print(f"An error occurred: {e}")
finally:
# Close the socket
client_socket.close()
if __name__ == "__main__":
# Command-line arguments: input_file output_file ip port
if len(sys.argv) != 5:
print("Usage: python udp_client.py <input_file> <output_file> <ip> <port>")
sys.exit(1)
input_file = sys.argv[1]
output_file = sys.argv[2]
ip = sys.argv[3]
port = int(sys.argv[4])
udp_client(input_file, output_file, ip, port)