-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwifile.py
More file actions
297 lines (258 loc) · 11.6 KB
/
wifile.py
File metadata and controls
297 lines (258 loc) · 11.6 KB
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
"""
WiFile - A simple command-line tool for transferring files over a network.
This module provides functionality to send and receive files between devices
on the same network using TCP sockets. It operates in two modes:
- Server mode: sends a file to connected clients
- Client mode: receives a file from a server
"""
import socket
import argparse
import os
import sys
import time
def format_bytes(bytes_value):
"""Convert bytes to human readable format."""
for unit in ['B', 'KB', 'MB', 'GB']:
if bytes_value < 1024.0:
return f"{bytes_value:.1f} {unit}"
bytes_value /= 1024.0
return f"{bytes_value:.1f} TB"
def show_progress(current, total, start_time=None):
"""Display a progress bar for file transfer."""
if total == 0:
return
percent = (current / total) * 100
bar_length = 50
filled_length = int(bar_length * current // total)
progress_bar = '█' * filled_length + '-' * (bar_length - filled_length)
current_formatted = format_bytes(current)
total_formatted = format_bytes(total)
progress_line = f'\r|{progress_bar}| {percent:.1f}% ({current_formatted}/{total_formatted})'
if start_time:
elapsed = time.time() - start_time
if elapsed > 0 and current > 0:
speed = current / elapsed
speed_formatted = format_bytes(speed)
eta_seconds = (total - current) / speed if speed > 0 else 0
eta_formatted = f"{int(eta_seconds)}s"
progress_line += f' - {speed_formatted}/s - ETA: {eta_formatted}'
print(progress_line, end='', flush=True)
if current >= total:
print() # New line when complete
def get_local_ip():
"""Get the local IP address of the machine."""
try:
# Create a socket and connect to a remote address to determine local IP
# This doesn't actually send data, just determines routing
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
s.connect(("8.8.8.8", 80))
local_ip = s.getsockname()[0]
return local_ip
except (socket.error, OSError):
# Fallback to localhost if we can't determine the actual IP
return "127.0.0.1"
def start_server(port, filepath):
"""Run the server to send a file to a client."""
if not os.path.isfile(filepath):
print(f"Error: File '{filepath}' does not exist.")
sys.exit(1)
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(('0.0.0.0', port)) # Listen on all interfaces
server_socket.listen(1)
local_ip = get_local_ip()
print(f"Server listening on port {port}")
print(f"Server IP address: {local_ip}")
print(
f"Clients can connect using: python wifile.py client --host {local_ip}")
print("Waiting for connection...")
conn = None
try:
conn, addr = server_socket.accept()
conn.settimeout(30) # 30 second timeout
print(f"Connected by {addr}")
# Send file name and size first
filename = os.path.basename(filepath)
filesize = os.path.getsize(filepath)
header = f"{filename}:{filesize}\n".encode()
conn.send(header)
# Wait for client acknowledgment
try:
ack = conn.recv(4) # Expect "ACK"
if ack != b"ACK\n":
print("Client did not acknowledge header properly")
return
except socket.timeout:
print("Timeout waiting for client acknowledgment")
return
# Send file content with progress bar
print(f"Sending '{filename}' ({format_bytes(filesize)})...")
sent_bytes = 0
start_time = time.time()
with open(filepath, 'rb') as f:
while True:
data = f.read(1024) # Read in 1KB chunks
if not data:
break
try:
conn.send(data)
sent_bytes += len(data)
show_progress(sent_bytes, filesize, start_time)
except (socket.error, ConnectionResetError, ConnectionAbortedError, BrokenPipeError) as e:
print(f"\nConnection lost during transfer: {e}")
transfer_msg = (f"Transfer incomplete: {format_bytes(sent_bytes)} "
f"of {format_bytes(filesize)} sent")
print(transfer_msg)
return
print(f"File '{filename}' sent successfully.")
except (socket.error, OSError, IOError) as e:
if "10054" in str(e) or "forcibly closed" in str(e).lower():
print(f"\nClient disconnected unexpectedly: {e}")
disconnect_msg = ("This usually means the client closed the connection "
"or network was interrupted.")
print(disconnect_msg)
else:
print(f"Server error: {e}")
finally:
if conn is not None:
conn.close()
server_socket.close()
def start_client(host, port, output_dir, auto_overwrite=False, auto_rename=False):
"""Run the client to receive a file from the server."""
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.settimeout(30) # 30 second timeout
try:
client_socket.connect((host, port))
print(f"Connected to server {host}:{port}")
# Receive file name and size
header_data = b""
while True:
chunk = client_socket.recv(1)
if not chunk:
raise ConnectionError(
"Connection closed while receiving header")
header_data += chunk
if header_data.endswith(b'\n'):
break
try:
header_str = header_data.decode('utf-8').strip()
filename, filesize = header_str.split(':')
filesize = int(filesize)
except (UnicodeDecodeError, ValueError) as e:
raise ValueError(f"Invalid header format: {e}") from e
# Send acknowledgment
client_socket.send(b"ACK\n")
output_path = os.path.join(output_dir, filename)
# Handle file conflicts
if os.path.exists(output_path):
if auto_overwrite:
print(f"Overwriting existing file '{filename}'...")
elif auto_rename:
base_name, ext = os.path.splitext(filename)
counter = 1
while True:
new_filename = f"{base_name}_{counter}{ext}"
new_output_path = os.path.join(output_dir, new_filename)
if not os.path.exists(new_output_path):
output_path = new_output_path
filename = new_filename
print(f"Saving as '{filename}' to avoid conflict...")
break
counter += 1
else:
print(
f"Warning: File '{filename}' already exists in '{output_dir}'")
while True:
choice = input(
"Choose action: (o)verwrite, (r)ename, (c)ancel: ").lower().strip()
if choice in ['o', 'overwrite']:
print(f"Overwriting existing file '{filename}'...")
break
elif choice in ['r', 'rename']:
base_name, ext = os.path.splitext(filename)
counter = 1
while True:
new_filename = f"{base_name}_{counter}{ext}"
new_output_path = os.path.join(
output_dir, new_filename)
if not os.path.exists(new_output_path):
output_path = new_output_path
filename = new_filename
print(f"Saving as '{filename}' instead...")
break
counter += 1
break
elif choice in ['c', 'cancel']:
print("Transfer cancelled by user.")
return
else:
print("Invalid choice. Please enter 'o', 'r', or 'c'.")
# Receive file content with progress bar
print(f"Receiving '{filename}' ({format_bytes(filesize)})...")
received = 0
start_time = time.time()
with open(output_path, 'wb') as f:
while received < filesize:
try:
data = client_socket.recv(1024)
if not data:
print("\nConnection closed by server. Transfer incomplete.")
received_msg = (f"Received: {format_bytes(received)} "
f"of {format_bytes(filesize)}")
print(received_msg)
break
f.write(data)
received += len(data)
show_progress(received, filesize, start_time)
except (socket.error, ConnectionResetError, ConnectionAbortedError) as e:
print(f"\nConnection lost during transfer: {e}")
received_msg = (f"Received: {format_bytes(received)} "
f"of {format_bytes(filesize)}")
print(received_msg)
break
if received == filesize:
print(f"File '{filename}' received and saved to '{output_path}'.")
else:
incomplete_msg = (f"Transfer incomplete. File saved as '{output_path}' "
"but may be corrupted.")
print(incomplete_msg)
except (socket.error, OSError, IOError, ValueError) as e:
if "10054" in str(e) or "forcibly closed" in str(e).lower():
print(f"Server disconnected unexpectedly: {e}")
disconnect_msg = ("This usually means the server closed the connection "
"or network was interrupted.")
print(disconnect_msg)
else:
print(f"Client error: {e}")
finally:
client_socket.close()
def main():
"""Parse command-line arguments and run the appropriate mode (server or client)."""
parser = argparse.ArgumentParser(
description="CLI tool for file transfer over WiFi network")
parser.add_argument(
'mode', choices=['server', 'client'], help="Run as server or client")
parser.add_argument('--port', type=int, default=12345,
help="Port to use (default: 12345)")
parser.add_argument(
'--file', help="Path to the file to send (server mode)")
parser.add_argument('--host', help="Server IP address (client mode)")
parser.add_argument('--output-dir', default=".",
help="Directory to save received file (client mode)")
parser.add_argument('--overwrite', action='store_true',
help="Automatically overwrite existing files (client mode)")
parser.add_argument('--auto-rename', action='store_true',
help="Automatically rename if file exists (client mode)")
args = parser.parse_args()
if args.mode == 'server':
if not args.file:
print("Error: --file is required in server mode.")
sys.exit(1)
start_server(args.port, args.file)
elif args.mode == 'client':
if not args.host:
print("Error: --host is required in client mode.")
sys.exit(1)
start_client(args.host, args.port, args.output_dir,
args.overwrite, args.auto_rename)
if __name__ == "__main__":
main()