How to Transfer Files in the Network using Sockets in Python

How to Transfer Files in the Network using Sockets in Python


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) 
file_path = input("Enter File Path : ") or '3'
file_path.replace("\\", "/")

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

    c,addr = s.accept()
    f = open(file_path, 'rb')
    datas =

    while datas:
        datas =



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( : ") or '3'
if ipcode=='3':
    print("empty input")
    print("Not! Connected")
    s.connect((ipcode, 5555))

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

        while True:
            datas = s.recv(1024)
            while datas:
                datas =s.recv(1024)

Run on mobile

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

img copyright by realpython


Great, we are done! It's working!

Did you find this article valuable?

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