The Wayback Machine - https://web.archive.org/web/20240906222943/https://www.geeksforgeeks.org/c-program-for-file-transfer-using-udp/
Open In App

C program for file Transfer using UDP

Last Updated : 30 Jul, 2019
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Data can be transferred between two computers using Socket programming in C.

Similarly, files can easily be sent using UDP protocol and a simple client/server.

Security: Handled by encryption.

Protocol : UDP
Encryption: XOR encryption

Algorithm :

1. The server starts and waits for filename.
2. The client sends a filename.
3. The server receives filename.
   If file is present,
   server starts reading file 
   and continues to send a buffer filled with
   file contents encrypted until file-end is reached.
4. End is marked by EOF.
5. File is received as buffers until EOF is 
received. Then it is decrypted.
6. If Not present, a file not found is sent.

The Server :




// server code for UDP socket programming
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
  
#define IP_PROTOCOL 0
#define PORT_NO 15050
#define NET_BUF_SIZE 32
#define cipherKey 'S'
#define sendrecvflag 0
#define nofile "File Not Found!"
  
// function to clear buffer
void clearBuf(char* b)
{
    int i;
    for (i = 0; i < NET_BUF_SIZE; i++)
        b[i] = '\0';
}
  
// function to encrypt
char Cipher(char ch)
{
    return ch ^ cipherKey;
}
  
// function sending file
int sendFile(FILE* fp, char* buf, int s)
{
    int i, len;
    if (fp == NULL) {
        strcpy(buf, nofile);
        len = strlen(nofile);
        buf[len] = EOF;
        for (i = 0; i <= len; i++)
            buf[i] = Cipher(buf[i]);
        return 1;
    }
  
    char ch, ch2;
    for (i = 0; i < s; i++) {
        ch = fgetc(fp);
        ch2 = Cipher(ch);
        buf[i] = ch2;
        if (ch == EOF)
            return 1;
    }
    return 0;
}
  
// driver code
int main()
{
    int sockfd, nBytes;
    struct sockaddr_in addr_con;
    int addrlen = sizeof(addr_con);
    addr_con.sin_family = AF_INET;
    addr_con.sin_port = htons(PORT_NO);
    addr_con.sin_addr.s_addr = INADDR_ANY;
    char net_buf[NET_BUF_SIZE];
    FILE* fp;
  
    // socket()
    sockfd = socket(AF_INET, SOCK_DGRAM, IP_PROTOCOL);
  
    if (sockfd < 0)
        printf("\nfile descriptor not received!!\n");
    else
        printf("\nfile descriptor %d received\n", sockfd);
  
    // bind()
    if (bind(sockfd, (struct sockaddr*)&addr;_con, sizeof(addr_con)) == 0)
        printf("\nSuccessfully binded!\n");
    else
        printf("\nBinding Failed!\n");
  
    while (1) {
        printf("\nWaiting for file name...\n");
  
        // receive file name
        clearBuf(net_buf);
  
        nBytes = recvfrom(sockfd, net_buf,
                          NET_BUF_SIZE, sendrecvflag,
                          (struct sockaddr*)&addr;_con, &addrlen;);
  
        fp = fopen(net_buf, "r");
        printf("\nFile Name Received: %s\n", net_buf);
        if (fp == NULL)
            printf("\nFile open failed!\n");
        else
            printf("\nFile Successfully opened!\n");
  
        while (1) {
  
            // process
            if (sendFile(fp, net_buf, NET_BUF_SIZE)) {
                sendto(sockfd, net_buf, NET_BUF_SIZE,
                       sendrecvflag, 
                    (struct sockaddr*)&addr;_con, addrlen);
                break;
            }
  
            // send
            sendto(sockfd, net_buf, NET_BUF_SIZE,
                   sendrecvflag,
                (struct sockaddr*)&addr;_con, addrlen);
            clearBuf(net_buf);
        }
        if (fp != NULL)
            fclose(fp);
    }
    return 0;
}


The Client:




// client code for UDP socket programming
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
  
#define IP_PROTOCOL 0
#define IP_ADDRESS "127.0.0.1" // localhost
#define PORT_NO 15050
#define NET_BUF_SIZE 32
#define cipherKey 'S'
#define sendrecvflag 0
  
// function to clear buffer
void clearBuf(char* b)
{
    int i;
    for (i = 0; i < NET_BUF_SIZE; i++)
        b[i] = '\0';
}
  
// function for decryption
char Cipher(char ch)
{
    return ch ^ cipherKey;
}
  
// function to receive file
int recvFile(char* buf, int s)
{
    int i;
    char ch;
    for (i = 0; i < s; i++) {
        ch = buf[i];
        ch = Cipher(ch);
        if (ch == EOF)
            return 1;
        else
            printf("%c", ch);
    }
    return 0;
}
  
// driver code
int main()
{
    int sockfd, nBytes;
    struct sockaddr_in addr_con;
    int addrlen = sizeof(addr_con);
    addr_con.sin_family = AF_INET;
    addr_con.sin_port = htons(PORT_NO);
    addr_con.sin_addr.s_addr = inet_addr(IP_ADDRESS);
    char net_buf[NET_BUF_SIZE];
    FILE* fp;
  
    // socket()
    sockfd = socket(AF_INET, SOCK_DGRAM,
                    IP_PROTOCOL);
  
    if (sockfd < 0)
        printf("\nfile descriptor not received!!\n");
    else
        printf("\nfile descriptor %d received\n", sockfd);
  
    while (1) {
        printf("\nPlease enter file name to receive:\n");
        scanf("%s", net_buf);
        sendto(sockfd, net_buf, NET_BUF_SIZE,
               sendrecvflag, (struct sockaddr*)&addr;_con,
               addrlen);
  
        printf("\n---------Data Received---------\n");
  
        while (1) {
            // receive
            clearBuf(net_buf);
            nBytes = recvfrom(sockfd, net_buf, NET_BUF_SIZE,
                              sendrecvflag, (struct sockaddr*)&addr;_con,
                              &addrlen;);
  
            // process
            if (recvFile(net_buf, NET_BUF_SIZE)) {
                break;
            }
        }
        printf("\n-------------------------------\n");
    }
    return 0;
}


Output :
Server :
server
Client :
client



Similar Reads

Difference between File Transfer Protocol (FTP) and Secure File Transfer Protocol (SFTP)
FTP (File Transfer Protocol) It is a protocol that is used to transfer or copy the file from one host to another host. But there may be some problems like different file names and different file directories while sending and receiving a files in different hosts or systems. And in FTP, a secure channel is not provided to transfer the files between t
3 min read
File transfer protocol server configuration using cisco packet tracer
In this article we are going to design a file transfer protocol server configuration in cisco packet tracer and checking the connectivity for uploading and downloading the file from remote PC. Objectives: To Configure FTP Services on Server.To Upload a File into the FTP Server from Remote PC.To Download a File from the FTP Server from Remote PC.Pro
3 min read
TCP and UDP server using select
Prerequisites: TCP UDP In previous articles, we have seen a TCP server and a UDP server. But now we can combine our concurrent TCP echo server and iterative UDP server into a single server that uses select to multiplex TCP and UDP socket. The Select function is used to select between TCP and UDP sockets. This function gives instructions to the kern
5 min read
Why is YouTube using TCP but not UDP?
Overview :In this article, we will discuss about which technology YouTube uses for streaming videos and music on its platform. YouTube is an American online video sharing and web-based media stage by Google. It is most utilized sites in the entire world. YouTube is a free video-facilitating site that permits individuals to store and serve video con
3 min read
What is Anonymous FTP (File Transfer Protocol)?
AFTP (Anonymous File Transfer Protocol) is a network protocol used for transmitting files using TCP-based networks. Anonymous file transfer protocol lets a user move files anonymously from one computer to another. Anonymous FTP operates at layer 7; anonymous FTP permits anonymous external computer users without any designated password or user ID to
3 min read
XMODEM File Transfer Protocol
XMODEM is a file transfer protocol which enables users to transmit files between different computers. History : XMODEM was developed by Ward Christensen in 1977 and since then the method of sharing files has changed. It became extremely popular in the early bulletin board system (BBS) market because of its simple implementation. However it became i
4 min read
SFTP File Transfer Protocol
SFTP (Secure File Transfer Protocol) is the advanced version of FTP(file transfer protocol) which ensures security while transferring files between the organizations/computer. It is also known as SSH(Secure Shell). It works on port no. 22 and uses the client-server model. Features of SFTP : It encrypts the data.It executes the command.It secures an
3 min read
What is TFTP (Trivial File Transfer Protocol)?
The network is made up of various devices. These devices are either connected by ethernet or by any wireless means. The communication for transferring files takes place between these connected devices. Therefore network protocols are required. Network protocols are defined as rules that describe the format of data, sending and receiving of data bet
5 min read
File Transfer Protocol (FTP) in Application Layer
FTP or File Transfer Protocol is said to be one of the earliest and also the most common forms of transferring files on the internet. Located in the application layer of the OSI model, FTP is a basic system that helps in transferring files between a client and a server. It is what makes the FTP unique that the system provides a reliable and efficie
11 min read
UDP Server-Client implementation in C++
There are two primary transport layer protocols to communicate between hosts: TCP and UDP. Creating TCP Server/Client was discussed in a previous post. Prerequisite: Creating TCP Server/Client Theory: In UDP, the client does not form a connection with the server like in TCP and instead sends a datagram. Similarly, the server need not accept a conne
4 min read
TCP and UDP in Transport Layer
Layer 3 or the Network layer uses IP or Internet Protocol which being a connection less protocol treats every packet individually and separately leading to lack of reliability during a transmission. For example, when data is sent from one host to another, each packet may take a different path even if it belongs to the same session. This means the p
4 min read
Various TCP and UDP ports
Transportation layer conventions utilize the idea of ports and multiplexing/demultiplexing to convey information to individual services listening on network nodes. These ports are spoken to by a solitary 16-bit number, implying that they can constitute a range of numbers 0-65535. This range has been separated by the IANA (Internet Assigned Numbers
4 min read
Difference between SCTP and UDP
1. Stream Control Transmission Protocol (SCTP): SCTP is a connection-oriented protocol in computer networks that provides full-duplex association i.e., Transmitting multiple streams of data between two endpoints at the same time that have been established connection in the network. 2. User Datagram Protocol (UDP): UDP is a Transport Layer protocol.
2 min read
Difference between UDP and RTP
1. User Datagram Protocol (UDP) : UDP is a Transport Layer protocol. It is a part of Internet Protocol suite, referred as UDP/IP suite. It is unreliable and connection-less protocol. Hence, there is no need to establish connection prior to data transfer. UDP sockets are an example of datagram sockets. It is more efficient in multicasting and broadc
2 min read
Examples on UDP Header
User Datagram Protocol is a Transport Layer protocol. UDP is a part of the Internet Protocol suite, referred to as UDP/IP suite. Unlike TCP, it is an unreliable and connectionless protocol. So, there is no need to establish a connection prior to data transfer. Though Transmission Control Protocol (TCP) is the dominant transport layer protocol used
4 min read
TCP vs UDP for Video Streaming
Prerequisite : TCP/IP Model, User Datagram Protocol (UDP)In this era of the modern internet with entertainment, education, gaming and all kinds of necessities streaming live everyday, the demand of an uninterrupted video stream is highly adamant. To dive into the topic of which protocol is better for video streaming, one must be familiar with the T
6 min read
Examples of TCP and UDP in Real Life
Today we will see the Real-Life Examples of TCP and UDP in Computer Networks Before looking at the Real-Life Examples of TCP and UDP, Let's see What is Computer Network? A Computer Network is a set of devices (Nodes) that are connected to each other by communication links to share digital information.The communication links can either be wireless m
8 min read
Why does Netflix use TCP but not UDP for streaming video?
Overview :In this article, we will discuss which technology Netflix uses for streaming online movies and web series on its platform. Netflix is an American subscription-based streaming service provider company. It is famous for streaming online videos, web series, and movies based on its subscription that its customers buy. There are two types of t
3 min read
How Applications Coexist Over TCP and UDP?
The Transport layer takes data from the Application layer, then it breaks into small segments called packets. Then handles them to the Network Layer for delivery. The transport layer uses two protocols which will be discussed here in this article. They are TCP ( Transmission Control Protocol ) and UDP ( User Datagram Protocol ). TCP ( Transmission
4 min read
Difference Between TCP, UDP and SCTP Protocols
In the realm of computer networking, different protocols play a vital role in facilitating the transmission of data across the internet. Three prominent protocols, TCP (Transmission Control Protocol), UDP (User Datagram Protocol), and SCTP (Stream Control Transmission Protocol), serve as the building blocks of modern network communication. Each of
6 min read
Why does DNS use UDP and not TCP?
DNS is an application layer protocol. All application layer protocols use one of the two transport layer protocols, UDP and TCP. TCP is reliable and UDP is not reliable. DNS is supposed to be reliable, but it uses UDP, why? There are the following interesting facts about TCP and UDP on the transport layer that justify the above. 1) UDP is much fast
2 min read
Why is UDP Faster than TCP?
In the study of Data Communication and Computer Networks TCP and UDP protocol is a very important concept. Both UDP and TCP are used in data transmission. UDP is faster than TCP but less reliable. We will learn here Why is UDP faster than TCP. UDP and TCP both are data transmission protocols. TCP is reliable but slower and in contrast, UDP is less
5 min read
How does UDP Work Without Connection?
Answer: By sending data packets directly to the recipient without establishing a prior connection, making it faster but less reliable than connection-oriented protocols.Datagram-BasedUDP is a datagram-oriented protocol, which means it sends data in small packets called datagrams independently of one another. No HandshakingUnlike TCP, UDP does not p
1 min read
Is UDP is a Two Way Connection?
Answer: No, UDP is not a two-way connection, it is a connectionless protocol that allows for two-way communication without establishing a persistent connection.Connectionless NatureUDP is inherently connectionless, meaning it does not establish a dedicated end-to-end connection before sending data. Bidirectional CommunicationDespite its connectionl
1 min read
How Checksum Computed in UDP?
Answer: The UDP checksum is a 16-bit one's complement sum of the UDP header, payload, and a pseudo-header with IP addresses, protocol, and UDP length.Inclusion of ComponentsIt starts with the aggregation of the UDP header, payload, and a pseudo-header, which is a construct that includes the source and destination IP addresses, the protocol indicati
1 min read
User Datagram Protocol (UDP)
User Datagram Protocol (UDP) is a Transport Layer protocol. UDP is a part of the Internet Protocol suite, referred to as UDP/IP suite. Unlike TCP, it is an unreliable and connectionless protocol. So, there is no need to establish a connection before data transfer. The UDP helps to establish low-latency and loss-tolerating connections over the netwo
10 min read
Differences between TCP and UDP
Transmission Control Protocol (TCP) and User Datagram Protocol (UDP) both are protocols of the Transport Layer Protocols. TCP is a connection-oriented protocol whereas UDP is a part of the Internet Protocol suite, referred to as the UDP/IP suite. Unlike TCP, it is an unreliable and connectionless protocol. In this article, we will discuss the diffe
9 min read
How to Transfer Files using SFTP?
SFTP (Secure File Transfer Protocol) or SSH (Secure Shell) File Transfer Protocol) is a file transfer protocol used to transfer files between client and server. It uses SSH(Secure Socket Shell) and is also known as Secure Socket Shell File Transfer Protocol. It provides secure access to a remote server for the secure transfer of files. Secure FTP a
3 min read
Asynchronous serial data transfer
In most computer asynchronous mode of data transfer is used in which two component have a different clock. Data transfer can occur between data in two ways serial and parallel. In case of parallel multiple lines are used to send a single bit whereas in serial transfer each bit is send one at a time. To tell other devices when the character/data wil
2 min read
Asynchronous Transfer Mode (ATM) in Computer Network
Why ATM networks? Driven by the integration of services and performance requirements of both telephony and data networking: "broadband integrated service vision" (B-ISON). Telephone networks support a single quality of service and are expensive to boot. Internet supports no quality of service but is flexible and cheap. ATM networks were meant to su
5 min read
Article Tags :