May-06-2020, 04:11 PM
I am not finding it easy to understand networking in Python, but with this code I have found I am getting the results I want but I would like to add some basic security to it, Username and Password. After hours of googling I am no wiser. Please help.
""" Server receiver of the file """ import socket import os # device's IP address SERVER_HOST = "127.1.1.0" SERVER_PORT = 1234 # receive 4096 bytes each time BUFFER_SIZE = 4096 SEPARATOR = "<SEPARATOR>" # create the server socket # TCP socket s = socket.socket() # bind the socket to our local address s.bind((SERVER_HOST, SERVER_PORT)) # enabling our server to accept connections # 5 here is the number of unaccepted connections that # the system will allow before refusing new connections s.listen(5) print(f"[*] Listening as {SERVER_HOST}:{SERVER_PORT}") # accept connection if there is any client_socket, address = s.accept() # if below code is executed, that means the sender is connected print(f"[+] {address} is connected.") # receive the file infos # receive using client socket, not server socket received = client_socket.recv(BUFFER_SIZE).decode() filename, filesize = received.split(SEPARATOR) # remove absolute path if there is filename = os.path.basename(filename) # convert to integer filesize = int(filesize) # start receiving the file from the socket # and writing to the file stream with open(filename, "wb") as f: for _ in range(filesize): # read 1024 bytes from the socket (receive) bytes_read = client_socket.recv(BUFFER_SIZE) if not bytes_read: # nothing is received # file transmitting is done break # write to the file the bytes we just received f.write(bytes_read) print(filename+' received') # close the client socket client_socket.close() # close the server socket s.close()
""" Client that sends the file (uploads) """ import socket import os SEPARATOR = "<SEPARATOR>" BUFFER_SIZE = 1024 * 4 #4KB def send_file(filename, host, port): # get the file size filesize = os.path.getsize(filename) # create the client socket s = socket.socket() print(f"[+] Connecting to {host}:{port}") s.connect((host, port)) print("[+] Connected.") # send the filename and filesize s.send(f"{filename}{SEPARATOR}{filesize}".encode()) # start sending the file with open(filename, "rb") as f: for _ in range(filesize): # read the bytes from the file bytes_read = f.read(BUFFER_SIZE) if not bytes_read: # file transmitting is done break # we use sendall to assure transmission in # busy networks s.sendall(bytes_read) # close the socket s.close() send_file(\\pathto\\myfile, "127.1.1.0", 1234)