import socket import threading import time import sys def parsespeedlimit(speedlimit):…
- User
import socket import threading import time import sys
def parse_speed_limit(speed_limit): """Parse the speed limit string and return bytes per second.""" if speed_limit[-1].upper() not in {'K', 'M', 'G'}: raise ValueError(f"Invalid speed limit unit: {speed_limit[-1]}") count = int(speed_limit[:-1]) units = {'K': 1024, 'M': 10242, 'G': 10243} return count * units[speed_limit[-1].upper()]
Dictionary to track clients and their data transfer statistics
clients_stats = {} clients_lock = threading.Lock()
def forward(source, destination, speed_limit_bps, client_id): """Forward data from source to destination at a limited speed, tracking stats.""" buffer_size = 4096 total_sent = 0 total_received = 0
codewhile True: # Receive data from the source data = source.recv(buffer_size) if not data: break # Exit if there's no data (connection closed) # Send data to the destination destination.sendall(data) total_sent += len(data) # Update the received data for the stats (from destination point of view) total_received += len(data) # Control the speed by sleeping as necessary if speed_limit_bps > 0: # Calculate current bytes per second elapsed_time = time.time() - start_time if elapsed_time > 0: current_bps = total_sent / elapsed_time if current_bps > speed_limit_bps: excess_time = (total_sent / speed_limit_bps) - elapsed_time if excess_time > 0: time.sleep(excess_time) # Clean up on exit source.close() destination.close() # Update statistics with clients_lock: clients_stats[client_id]['sent'] += total_sent clients_stats[client_id]['received'] += total_receiveddef start_forwarder(local_host, local_port, remote_host, remote_port, speed_limit): speed_limit_bps = parse_speed_limit(speed_limit)
code - Assistant