ProDeveloperTutorial.com

Tutorials and Programming Solutions
Menu
  • Shell Scripting
  • System Design
  • Linux System Programming
  • 4g LTE
  • Coding questions
  • C
  • C++
  • DSA
  • GIT
  • 450 DSA Cracker
  • 5G NR
  • O-RAN

Linux System Programming: Creating UDP sockets

prodevelopertutorial May 22, 2020

In this chapter we shall learn about:

1. Introduction

2. API’s for creating a UDP server:

3. API’s for creating a UDP client:

4. API prototypes

5. Example: UDPServer.c

6. Example: UDPClient.c

 

Creating UDP sockets

The above image shows the sequence of steps for a Server and client to create a UDP client server communication.

For creating a UDP server:

1. Create a socket using “socket()”
2. bind to an address using “bind()”
3. Wait for the data to be received using “recvfrom()”
4. Send the data to client using “sendto()”
5. Close the connection using “close()”

For creating a UDP client:

1. Create a socket using “socket()”
2. bind to an address using “bind()”
3. Send the data to server using “sendto()”
4. Receive the data from the server using “recvfrom()”
5. Close the connection using “close()”

Important header files to be included in UDP socket programming:

#include <sys/socket.h>		It contains the data structures required for socket 

#include <netinet/in.h>		It has the constants and structures required for Internet domain address.

#include <sys/types.h>		It has definitions of number of data types used for system calls.

Now let us understand the API’s involved in creating a server and client.

Important API used in UDP socket programming:

1. Create a socket using “socket()” system call

int sockID =socket(family, type, protocol);
sockID is a file descriptor.
family: It is an integer in communication domain.
There are 2 possible domains:
1. Unix Domain: Where 2 process share the same file system. In that case family will be “AF_UNIX”
2. Internet Domain: They are 2 hosts on the Internet.In that case family will be “AF_INET”
type: It is the type of communication.
SOCK_STREAM: For TCP
SOCK_DGRAM: For UDP
protocol: It will specify the protocol.
IPPROTO_TCP, IPPROTO_UDP.
But it is always set to 0, so that OS will choose appropriate protocol.
This API will return -1 upon failure.

2. Closing a socket using “close()” system call.

A socket created must be closed after the transmission is completed.

status = close(sockid);
sockid: It is the file descriptor of the socket being closed.
status: 0 if successful -1 if error.

3. Important Data Structures for specifying address:

1. sockaddr:
It defines a generic data type for address. We use sockaddr_in to be casted to sockaddr.

struct sockaddr{

unsigned short sa_family; // address family AF_INET
char sa_sata[14]; // Family specific address information
}
2. in_addr:
It is the internet address

struct in_addr{
unsigned long s_addr; // internet address 32 bits
}
3. sockaddr_in

struct sockaddr_in{
unsigned short sin_family; // address family AF_INET
unsigned short sin_port; // assign the port
struct in_addr sin_addr; // assign the ip address
char sin_ero[8];

}

4. Assign address to a socket using “bind()” api

int status = bind (sockid, &addrport, size)
sockid = It is the socket descriptor that we created earlier.
addrPort: it is the filled part of the structure sockaddr_in, casted to sockaddr.
size: It is the size of sockaddr_in.
status: It will return -1 if failure.

5. Send the data using “sendto()”:

int count = sendto(sockid, msg, msgLen, flags, &serverAddr, addrlen);
msg: It is the message to be transmitted.
msgLen: Length of the message
flags: Special options, usually 0
serverAddr: Address of server
addrlen: address of sockaddr_in.

6. Receive the data using “recvfrom()”:

int count = recvfrom(sockid, recvBuf, bufLen, flags, &clientAddr, addrlen);
recvBuf: It is the message to be received.
bufLen: Length of the message
flags: Special options, usually 0
clientAddr: Address of client.
addrlen: address of sockaddr_in.

Code for UDP server:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>

int main( )
{

  int port = 1234;
  int sockfd;
  struct sockaddr_in si_me, si_other;
  char buffer[1024];
  socklen_t addr_size;

  sockfd = socket(AF_INET, SOCK_DGRAM, 0);

  memset(&si_me, '\0', sizeof(si_me));
  si_me.sin_family = AF_INET;
  si_me.sin_port = htons(port);
  si_me.sin_addr.s_addr = inet_addr("127.0.0.1");

  bind(sockfd, (struct sockaddr*)&si_me, sizeof(si_me));
  addr_size = sizeof(si_other);
  recvfrom(sockfd, buffer, 1024, 0, (struct sockaddr*)& si_other, &addr_size);
  printf("[+]Data Received: %s", buffer);

  return 0;
}

Code for UDP client:

 

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>

int main()
{

  int port = 1234;
  int sockfd;
  struct sockaddr_in serverAddr;
  char buffer[1024];
  socklen_t addr_size;

  sockfd = socket(PF_INET, SOCK_DGRAM, 0);
  memset(&serverAddr, '\0', sizeof(serverAddr));

  serverAddr.sin_family = AF_INET;
  serverAddr.sin_port = htons(port);
  serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");

  strcpy(buffer, "Hello Server\n");
  sendto(sockfd, buffer, 1024, 0, (struct sockaddr*)&serverAddr, sizeof(serverAddr));
  printf("[+]Data Send: %s", buffer);

  return 0;


}

Output:

[+]Data Received: Hello Server

List Of Tutorials available in this website:

C Programming 20+ ChaptersC++ Programming 80+ Chapters
100+ Solved Coding QuestionsData Structures and Algorithms 85+ Chapters
System design 20+ ChaptersShell Scripting 12 Chapters
4g LTE 60+ ChaptersMost Frequently asked Coding questions
5G NR 50+ ChaptersLinux System Programming 20+ chapters
Share
Email
Tweet
Linkedin
Reddit
Stumble
Pinterest
Prev Article
Next Article

About The Author

prodevelopertutorial

Follow this blog to learn more about C, C++, Linux, Competitive Programming concepts, Data Structures.

Leave a Reply Cancel Reply

You must be logged in to post a comment.

ProDeveloperTutorial.com

Tutorials and Programming Solutions
Copyright © 2023 ProDeveloperTutorial.com
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept”, you consent to the use of ALL the cookies.
Do not sell my personal information.
Cookie SettingsAccept
Manage consent

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.
CookieDurationDescription
cookielawinfo-checkbox-analytics11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checkbox-functional11 monthsThe cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checkbox-necessary11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-others11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-performance11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
viewed_cookie_policy11 monthsThe cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.
Functional
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Performance
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Analytics
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
Advertisement
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.
Others
Other uncategorized cookies are those that are being analyzed and have not been classified into a category as yet.
SAVE & ACCEPT