Sendfile() Function Of Os Module In Python


sendfile(out_fd, in_fd, offset, count)


  • The sendfile() function copies the contents of one file to another file, using their descriptors.


out_fd - The descriptor of the destination file

in_fd  - The descriptor of the source file

offset - Offset from where the contents need to be copied from the source

count  - Number of bytes to be copied

Return Value:


Example Client Program:

# Example client program that sends the text of a song
# from a file over a streaming socket to the server
import os
import socket

# The file to be sent and its descriptor
srcPath = "/PythonProgs/BaaBaa.txt"
srcDesc     =, os.O_RDONLY, 0o744)

# Create a client connection
socketObject = socket.socket()
socketObject.connect(("localhost", 34422))

# In macOS, a zero value for the count means
# to send all the file contents
os.sendfile(socketObject.fileno(), srcDesc, 0, 0)
data = socketObject.recv(2048)


b'The wheels on the bus go round and round'

Example - Server Program:

# Example server program that sends
# a song to its client connections using
# os.sendfile() function
import socket
import os

# Create a streaming server socket(i.e,TCP server) that
# uses Internet Protocol v4 addressing scheme
svr = socket.socket()
print("Server socket created")

ip      = ""
port    = 34422
svr.bind((ip, port))
print("Server bound with ip {} port {}".format(ip, port))

# Listen for connection requests

# Serve connection requests
count = 0

    (client, clientIP) = svr.accept()
    count = count + 1
    print("Accepted {} connections till now".format(count))
        # Recv msgs upto 1 KB    
        data = client.recv(1024)
            # Send the song, "Wheels on the bus..."" as reply to clients
            srcFilePath = "/PythonProgs/Wheels.txt"
            srcDesc  =, os.O_RDONLY, 0o744)
            # Get the file descriptor associated with the socket
            clientDesc = client.fileno()            
            os.sendfile(clientDesc, srcDesc, 0, 0)
            print("Client connection closed")


Server socket created
Server bound with ip port 34422
Accepted 1 connections till now
b'Baa, baa, black sheep,\nHave you any wool?\nYes, sir, yes, sir,\nThree bags full;\nOne for my master,\nAnd one for my dame,\nand one for the little boy\nWho lives down the lane.'
Client connection closed

Copyright 2023 ©