python upload file to socket server udp

· 8 min read · Updated jan 2022 · Python Standard Library

Disclosure: This post may comprise chapter links, meaning when you lot click the links and make a purchase, we receive a commission.

File transfer is the process of copying or moving a file from one computer to another over a network or Net connection. In this tutorial, we'll go step by step on how you tin write client/server Python scripts that handles that.

The basic idea is to create a server that listens on a particular port; this server will be responsible for receiving files (you can brand the server send files as well). On the other hand, the client will try to connect to the server and send a file of whatever blazon.

We will use the socket module, which comes born with Python and provides united states of america with socket operations that are widely used on the Internet, as they are backside whatever connection to any network.

Delight note that there are more reliable ways to transfer files with tools like rsync or scp. Nonetheless, the goal of this tutorial is to transfer files with Python programming language and without any third-political party tool.

Related: How to Organize Files by Extension in Python.

First, we gonna need to install the tqdm library, which will enable us to print fancy progress confined:

          pip3 install tqdm        

Client Code

Let's start with the client, the sender:

          import socket import tqdm import os  SEPARATOR = "<SEPARATOR>" BUFFER_SIZE = 4096 # send 4096 bytes each time stride        

We need to specify the IP address, the port of the server we desire to connect to, and the name of the file we desire to send.

          # the ip address or hostname of the server, the receiver host = "192.168.1.101" # the port, let's utilize 5001 port = 5001 # the name of file we want to transport, make sure it exists filename = "data.csv" # get the file size filesize = os.path.getsize(filename)        

The filename needs to exist in the current directory, or you can utilize an absolute path to that file somewhere on your computer. This is the file you want to send.

os.path.getsize(filename) gets the size of that file in bytes; that's smashing, as we need information technology for printing progress confined in the customer and the server.

Let's create the TCP socket:

          # create the customer socket s = socket.socket()        

Connecting to the server:

          print(f"[+] Connecting to {host}:{port}") s.connect((host, port)) impress("[+] Continued.")        

connect() method expects an accost of the pair (host, port) to connect the socket to that remote address. In one case the connection is established, nosotros need to send the proper name and size of the file:

          # send the filename and filesize s.send(f"{filename}{SEPARATOR}{filesize}".encode())        

I've used SEPARATOR here to separate the data fields; information technology is just a junk message, nosotros can but use send() twice, simply we may not desire to practice that anyhow. encode() role encodes the string we passed to 'utf-viii' encoding (that's necessary).

Now we need to send the file, and every bit we are sending the file, we'll print nice progress confined using the tqdm library:

          # kickoff sending the file progress = tqdm.tqdm(range(filesize), f"Sending {filename}", unit of measurement="B", unit_scale=True, unit_divisor=1024) with open(filename, "rb") as f:     while Truthful:         # read the bytes from the file         bytes_read = f.read(BUFFER_SIZE)         if not bytes_read:             # file transmitting is done             suspension         # we use sendall to assure transimission in          # decorated networks         southward.sendall(bytes_read)         # update the progress bar         progress.update(len(bytes_read)) # close the socket southward.close()        

Basically, what we are doing here is opening the file as read in binary, read chunks from the file (in this case, 4096 bytes or 4KB) and sending them to the socket using the sendall() function, and then we update the progress bar each time, once that's finished, we close that socket.

Related: How to Make a Chat Application in Python.

Server Code

Alright, so we are done with the client. Let's dive into the server, so open up a new empty Python file and:

          import socket import tqdm import os # device's IP address SERVER_HOST = "0.0.0.0" SERVER_PORT = 5001 # receive 4096 bytes each fourth dimension BUFFER_SIZE = 4096 SEPARATOR = "<SEPARATOR>"        

I've initialized some parameters nosotros are going to utilise. Notice that I've used "0.0.0.0" equally the server IP address. This means all IPv4 addresses that are on the local machine. You may wonder why we don't simply apply our local IP accost or "localhost" or "127.0.0.1"? Well, if the server has two IP addresses, permit's say "192.168.1.101" on a network and "10.0.1.i" on some other, and the server listens on "0.0.0.0", it volition exist reachable at both of those IPs.

Alternatively, you can utilise your public or private IP accost, depending on your clients. If the connected clients are in your local network, you should use your individual IP (you can check it using ipconfig command in Windows or ifconfig command in Mac OS/Linux), but if you're expecting clients from the Net, you definitely should use your public address.

Too, Make sure you utilize the same port in the server as in the client.

Let's create our TCP socket:

          # create the server socket # TCP socket s = socket.socket()        

Now, this is unlike from the client, and we need to bind the socket we but created to our SERVER_HOST and SERVER_PORT:

          # demark the socket to our local accost s.bind((SERVER_HOST, SERVER_PORT))        

After that, we are going to listen for connections:

          # enabling our server to accept connections # v here is the number of unaccepted connections that # the organization will permit before refusing new connections s.listen(5) print(f"[*] Listening as {SERVER_HOST}:{SERVER_PORT}")        

Once the client connects to our server, we need to accept that connexion:

          # accept connexion if at that place is any client_socket, address = south.take()  # if below code is executed, that means the sender is connected print(f"[+] {accost} is connected.")        

Remember that when the client is connected, it'll transport the name and size of the file. Let's receive them:

          # 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 at that place is filename = os.path.basename(filename) # convert to integer filesize = int(filesize)        

Equally mentioned earlier, the received information is combined with the filename and the filesize, and we can easily extract them by splitting them by the SEPARATOR cord.

After that, we demand to remove the file'southward absolute path considering the sender sent the file with his own file path, which may differ from ours, the os.path.basename() role returns the final component of a path name.

Now we need to receive the file:

          # start receiving the file from the socket # and writing to the file stream progress = tqdm.tqdm(range(filesize), f"Receiving {filename}", unit="B", unit_scale=True, unit_divisor=1024) with open(filename, "wb") as f:     while True:         # read 1024 bytes from the socket (receive)         bytes_read = client_socket.recv(BUFFER_SIZE)         if non bytes_read:                 # cypher is received             # file transmitting is done             break         # write to the file the bytes we just received         f.write(bytes_read)         # update the progress bar         progress.update(len(bytes_read))  # shut the customer socket client_socket.close() # shut the server socket southward.close()        

Not entirely different from the client code. However, nosotros are opening the file as write in binary hither and using the recv(BUFFER_SIZE) method to receive BUFFER_SIZE bytes from the client socket and write information technology to the file. Once that'south finished, we shut both the client and server sockets.

Learn also: How to List all Files and Directories in FTP Server using Python

Alright, allow me try it on my own individual network:

          C:\> python receiver.py  [*] Listening as 0.0.0.0:5001        

I need to go to my Linux box and send an example file:

          [electronic mail protected]:~/tools# python3 sender.py [+] Connecting to 192.168.1.101:5001 [+] Connected. Sending data.npy:   9%|███████▊                                                                            | 45.5M/487M [00:14<02:01, 3.80MB/s]        

Let's meet the server now:

          [+] ('192.168.1.101', 47618) is connected. Receiving data.npy:  33%|███████████████████▍                                       | 160M/487M [01:04<04:xv, 1.34MB/due south]        

Corking, we are done!

You tin extend this lawmaking for your own needs now. Here are some examples you can implement:

  • Enabling the server to receive multiple files from multiple clients simultaneously using threads.
  • Compressing the files before sending them which may help increase the transfer duration. If the target files yous want to send are images, you can optimize images by compressing them.
  • Encrypting the file earlier sending it to ensure that no one tin can intercept and read that file, this tutorial will aid.
  • Ensuring the file is appropriately sent by checking the checksums of both files (the original file of the sender and the sent file in the receiver). In this example, yous demand secure hashing algorithms to do information technology.
  • Adding a conversation room and then you can both chat and transfer files.

Finally, if you're a beginner and want to learn Python, I suggest you take Master Python in five Online Courses from the University of Michigan, in which you'll learn a lot about Python, good luck!

Read Also: How to Manipulate IP Addresses in Python

Happy Coding ♥

View Full Code


Read Also


How to Organize Files by Extension in Python

How to Create a Reverse Shell in Python

How to Download Files from URL in Python


Annotate panel

joneswaallovar.blogspot.com

Source: https://www.thepythoncode.com/article/send-receive-files-using-sockets-python

0 Response to "python upload file to socket server udp"

Postar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel