ComputerNetworksAndSecurity/Codes/Code-B9 (Sender).py

31 lines
868 B
Python

import socket
import os
def send_file(filename, host, port):
# Create a UDP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# Get file size
filesize = os.path.getsize(filename)
sock.sendto(f"{filename}:{filesize}".encode(), (host, port))
with open(filename, "rb") as f:
print(f"Sending {filename}...")
bytes_sent = 0
while bytes_sent < filesize:
data = f.read(1024) # Read in chunks
sock.sendto(data, (host, port))
bytes_sent += len(data)
print(f"File {filename} sent successfully.")
sock.close()
if __name__ == "__main__":
target_host = input("Enter the receiver's IP address: ")
target_port = int(input("Enter the receiver's port: "))
# Choose a file to send
filename = input("Enter the file path to send (Text, Audio, Video, or Script): ")
send_file(filename, target_host, target_port)