How to Transfer Files in the Network using Sockets in Python

How to Transfer Files in the Network using Sockets in Python

Information

File transfer is the process of copying or moving a file from one computer to another over a network or Internet connection. In this tutorial, we'll go step by step on how you can 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 make the server send files as well). On the other hand, the client will try to connect to the server and send a file of any type.

We will use the socket module, which comes built-in with Python and provides us with socket operations that are widely used on the Internet, as they are behind any connection to any network.

Server Code

Let's start with the Server, the sender, so open up a new empty Python file and write this code

import socket

hostname = socket.gethostname()
IPAddr = socket.gethostbyname(hostname)   
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

print("HostName is : " + hostname)   
print("IP Address is : " + IPAddr) 
print('\n')
file_path = input("Enter File Path : ") or '3'
file_path.replace("\\", "/")

if file_path=='3':
    print("Empty Input")
else:
    # ip address of computer 
    s.bind((IPAddr, 5555))

    s.listen(10)
    c,addr = s.accept()
    f = open(file_path, 'rb')
    datas = f.read(1024)

    while datas:
        c.send(datas)
        datas = f.read(1024)

    f.close()

    print('Sended...')

Client Code

Let's start with the client to receive files, so open up a new empty python file and write this code

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

ipcode = input("Enter IP Address ex(192.168.43.150) : ") or '3'
if ipcode=='3':
    print("empty input")
    print("Not! Connected")
else:
    s.connect((ipcode, 5555))

    extension = input("Enter File Extension without dote ex:(png, mp4) : ") or '3'
    if extension=='3':
        print("empty input")
    else:
        f = open(f'download.{extension}', 'wb')

        while True:
            datas = s.recv(1024)
            while datas:
                f.write(datas)
                datas =s.recv(1024)
            f.close()
            break
        print("Downloaded...")

Run on mobile

Use termux, and install python using this command pkg install python

img copyright by realpython

Conclusion

Great, we are done! It's working!

Did you find this article valuable?

Support Amit Gajare by becoming a sponsor. Any amount is appreciated!