Engineers Garage

  • Electronic Projects & Tutorials
    • Electronic Projects
      • Arduino Projects
      • AVR
      • Raspberry pi
      • ESP8266
      • BeagleBone
      • 8051 Microcontroller
      • ARM
      • PIC Microcontroller
      • STM32
    • Tutorials
      • Audio Electronics
      • Battery Management
      • Brainwave
      • Electric Vehicles
      • EMI/EMC/RFI
      • Hardware Filters
      • IoT tutorials
      • Power Tutorials
      • Python
      • Sensors
      • USB
      • VHDL
    • Circuit Design
    • Project Videos
    • Components
  • Articles
    • Tech Articles
    • Insight
    • Invention Stories
    • How to
    • What Is
  • News
    • Electronic Product News
    • Business News
    • Company/Start-up News
    • DIY Reviews
    • Guest Post
  • Forums
    • EDABoard.com
    • Electro-Tech-Online
    • EG Forum Archive
  • DigiKey Store
    • Cables, Wires
    • Connectors, Interconnect
    • Discrete
    • Electromechanical
    • Embedded Computers
    • Enclosures, Hardware, Office
    • Integrated Circuits (ICs)
    • Isolators
    • LED/Optoelectronics
    • Passive
    • Power, Circuit Protection
    • Programmers
    • RF, Wireless
    • Semiconductors
    • Sensors, Transducers
    • Test Products
    • Tools
  • Learn
    • eBooks/Tech Tips
    • Design Guides
    • Learning Center
    • Tech Toolboxes
    • Webinars & Digital Events
  • Resources
    • Digital Issues
    • EE Training Days
    • LEAP Awards
    • Podcasts
    • Webinars / Digital Events
    • White Papers
    • Engineering Diversity & Inclusion
    • DesignFast
  • Guest Post Guidelines
  • Advertise
  • Subscribe

Communication between server- client through socket programming using UDP/IP (21/24)

By Ashish Vara September 22, 2016

Communication between server- client through socket programming using UDP/IP

In the previous tutorial, I explained about communication between server-client through socket programming. We can also establish server-client communication using UDP/IP. In this tutorial, I will explain how communication occurs between server-client through UDP/IP. Before explanation, let’s see some basic view of terminology. 
 
Three main things  are needed to establish connection between server-client models:
1) Transport protocol (TCP or UDP)
2) Socket
3) IP address and port
 
Transport protocol (UDP)
 
UDP is a connection-less protocol which stands for user datagram protocol. It is an unreliable protocol but with IP it provides the best communication mechanism. Many characteristics are similar to TCP but not all. IN UDP, the receiver cannot generate the acknowledgement of received packet so sender (client) can send data without waiting for the acknowledgement. 
 
Socket
 
The socket is the end point connection for communication between two machines. It seems like data connectivity path between two wireless terminals. The socket is required at both sides of server and client. You can refer to the tutorial socket and How to create a socket in Linux.
 
IP address and port
 
IP address is a unique numerical address of each computer and device. It  plays an important role in networking domain with Internet protocol. In server – client model, the server needs to know as to which device is connected with it and with whom server establishes the connection. IP address  plays an important role in communication between server-client models.
In terms of networking, the port is the location where information is sent. Various protocols assign different port numbers. The specific port number is required to communicate between server-client according to which protocol is used.
 
Let’s  check  how to get user’s IP address. Enter the following command from command terminal:
 
ifconfig
 
It displays network information like address, data packet etc. Be sure which type of Internet connection is there in your system.
 The IP address of the system is located by “inet addr”. It is your system’s IP address.
 
For example, inet addr: xxx.xx.xx.xx 
 
Here, x represents numerical value.
 
Server- client socket programming
Let’s  look at server –client communication through socket programming. I assume that you know about the basic C programming and socket. If not,  kindly refer to the tutorial socket and How to create socket in Linux before learning this tutorial. 
 
Here I have  written two individual programs, one for sever side and one for client side. We need  to have a computer with Linux environment. But do not  worry; you can communicate with the only single system. 
 
Server side
//*******************************udp_server.c*******************************//
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
 
int main()
{
        int sock;
        int IPlength, TotalByte;
        char message[512];
        struct sockaddr_in serverAdd , clientAdd;
        if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
        {
            perror(“Socket Creation Failed”);
            exit(1);
        }
        serverAdd.sin_family = AF_INET;
        serverAdd.sin_port = htons(5000);
        serverAdd.sin_addr.s_addr = INADDR_ANY;
        bzero(&(serverAdd.sin_zero),8);
        if (bind(sock,(struct sockaddr *)&serverAdd,sizeof(struct sockaddr)) == -1)
        {
            perror(“Bind Error”);
            exit(1);
        }
        IPlength = sizeof(struct sockaddr);
        printf(“nUDP Server Waiting for client Messagen”);
        fflush(stdout);
        while (1)
        {
TotalByte = recvfrom(sock,message,512,0,(struct sockaddr *)&clientAdd, &IPlength);
message[TotalByte] = ‘’;
            printf(“Received Message: %s”, message);
fflush(stdout);
        }
        return 0;
}
//*******************************udp_server.c*******************************//
 
Save the file in directory and compile it. After successful compilation, run the executable file from command terminal. You may refer to the tutorial How to make first C program in Linux if you are not aware of compilation and execution process.
 
The following tasks  are done at server side program:
– Define the necessary library file  at server side
– Create a socket for end point communication 
– Define the UDP protocol (i.e SOCK_DGRAM) and bind the communication port (in this case: port number is 5000).
– After successful binding, server waits  to receive the data from client 
– If data is received from client, the server displays it on the command terminal.
 
 
Client side
//*******************************udp_client.c*******************************//
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
 
int main()
{
int sock;
struct sockaddr_in serverAdd;
struct hostent *host;
char sendMessage[512];
host= (struct hostent *) gethostbyname((char *)”Server’s IP address”);
if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
{
perror(“socket Creation Failed”);
exit(1);
}
serverAdd.sin_family = AF_INET;
serverAdd.sin_port = htons(5000);
serverAdd.sin_addr = *((struct in_addr *)host->h_addr);
bzero(&(serverAdd.sin_zero),8);
 
    while (1)
    {
    printf(“Enter the Message:”);
    fgets(sendMessage,100,stdin);
sendto(sock, sendMessage, strlen(sendMessage), 0,(struct sockaddr   *)&serverAdd, sizeof(struct sockaddr));
  memset (sendMessage , 0 , sizeof(sendMessage));
        }
}
//*******************************udp_client.c*******************************//
Save the file in directory and compile it. After successful compilation, run the executable file from command terminal. You  may refer to the tutorial How to make first C program in Linux if you are not aware of compilation and execution process.
 
Note: Write down your server’s IP address in place of  “Server’s IP address” .
 
For example,
 host= (struct hostent *) gethostbyname((char *)”123.456.78.9″);
It is only an example; your server IP address  may be different  from the example.
 
The following tasks  are done at client side program:
– Define the necessary library file at client side
– Create a socket for end point communication 
– Define the UDP protocol (i.e SOCK_DGRAM) and bind the communication port (in this case: port number is 5000).
– After successful binding, the client can communicate with the server.
– Now, the user can send the data from terminal.
 
Run server –client program on the same system
 
You can run the server-client program on the same machine. First find your client PC’s IP address as I have described above. Now  if you want to run it on same PC, same IP is entered in source code of client. Save both the source code of server and client on the same PC.
 
Open the command terminal and run server side executable file. As the  server side code is in running mode,  don’t interrupt from code. Open another command terminal and run client side executable file.
 
Screenshot of Command Terminal
 
Fig. 1: Screenshot of Command Terminal
 
 
Now enter some data from command terminal where client-side program is running. You can see the data is received and displayed on server side command terminal. 
 
Screenshot of Data Received and Displayed on Server Side Command Terminal
 
Fig. 2: Screenshot of Data Received and Displayed on Server Side Command Terminal
 

Filed Under: Tutorials

 

Next Article

← Previous Article
Next Article →

Questions related to this article?
👉Ask and discuss on Electro-Tech-Online.com and EDAboard.com forums.



Tell Us What You Think!! Cancel reply

You must be logged in to post a comment.

EE TECH TOOLBOX

“ee
Tech Toolbox: 5G Technology
This Tech Toolbox covers the basics of 5G technology plus a story about how engineers designed and built a prototype DSL router mostly from old cellphone parts. Download this first 5G/wired/wireless communications Tech Toolbox to learn more!

EE Learning Center

EE Learning Center
“engineers
EXPAND YOUR KNOWLEDGE AND STAY CONNECTED
Get the latest info on technologies, tools and strategies for EE professionals.

HAVE A QUESTION?

Have a technical question about an article or other engineering questions? Check out our engineering forums EDABoard.com and Electro-Tech-Online.com where you can get those questions asked and answered by your peers!


RSS EDABOARD.com Discussions

  • No Output Voltage from Voltage Doubler Circuit in Ansys Nexxim (Harmonic Balance Simulation)
  • Discrete IrDA receiver circuit
  • How do loop recording and G-sensors work on front and rear dash cams?
  • Getting different output for op amp circuit
  • Resistor Selection for Amplifier Layout

RSS Electro-Tech-Online.com Discussions

  • Saga 1400sv vinyl cutter motherboard issue
  • PIC KIT 3 not able to program dsPIC
  • Wideband matching an electrically short bowtie antenna; 50 ohm, 434 MHz
  • using a RTC in SF basic
  • Relay buzzing after transformer change?

Featured – RPi Python Programming (27 Part)

  • RPi Python Programming 21: The SIM900A AT commands
  • RPi Python Programming 22: Calls & SMS using a SIM900A GSM-GPRS modem
  • RPi Python Programming 23: Interfacing a NEO-6MV2 GPS module with Raspberry Pi
  • RPi Python Programming 24: I2C explained
  • RPi Python Programming 25 – Synchronous serial communication in Raspberry Pi using I2C protocol
  • RPi Python Programming 26 – Interfacing ADXL345 accelerometer sensor with Raspberry Pi

Recent Articles

  • GigaDevice launches GD32C231 MCU series with 48MHz Cortex-M23 core and 64KB Flash
  • Advanced Energy releases 425 W CF-rated medical power supply in 3.5 x 6 x 1.5-inch format”
  • LEM combines shunt and Hall effect sensing in 2000 A current measurement unit
  • What is AWS IoT Core and when should you use it?
  • AC-DC power supply extends voltage range to 800 V DC

EE ENGINEERING TRAINING DAYS

engineering

Submit a Guest Post

submit a guest post
Engineers Garage
  • Analog IC TIps
  • Connector Tips
  • Battery Power Tips
  • DesignFast
  • EDABoard Forums
  • EE World Online
  • Electro-Tech-Online Forums
  • EV Engineering
  • Microcontroller Tips
  • Power Electronic Tips
  • Sensor Tips
  • Test and Measurement Tips
  • 5G Technology World
  • Subscribe to our newsletter
  • About Us
  • Contact Us
  • Advertise

Copyright © 2025 WTWH Media LLC. All Rights Reserved. The material on this site may not be reproduced, distributed, transmitted, cached or otherwise used, except with the prior written permission of WTWH Media
Privacy Policy

Search Engineers Garage

  • Electronic Projects & Tutorials
    • Electronic Projects
      • Arduino Projects
      • AVR
      • Raspberry pi
      • ESP8266
      • BeagleBone
      • 8051 Microcontroller
      • ARM
      • PIC Microcontroller
      • STM32
    • Tutorials
      • Audio Electronics
      • Battery Management
      • Brainwave
      • Electric Vehicles
      • EMI/EMC/RFI
      • Hardware Filters
      • IoT tutorials
      • Power Tutorials
      • Python
      • Sensors
      • USB
      • VHDL
    • Circuit Design
    • Project Videos
    • Components
  • Articles
    • Tech Articles
    • Insight
    • Invention Stories
    • How to
    • What Is
  • News
    • Electronic Product News
    • Business News
    • Company/Start-up News
    • DIY Reviews
    • Guest Post
  • Forums
    • EDABoard.com
    • Electro-Tech-Online
    • EG Forum Archive
  • DigiKey Store
    • Cables, Wires
    • Connectors, Interconnect
    • Discrete
    • Electromechanical
    • Embedded Computers
    • Enclosures, Hardware, Office
    • Integrated Circuits (ICs)
    • Isolators
    • LED/Optoelectronics
    • Passive
    • Power, Circuit Protection
    • Programmers
    • RF, Wireless
    • Semiconductors
    • Sensors, Transducers
    • Test Products
    • Tools
  • Learn
    • eBooks/Tech Tips
    • Design Guides
    • Learning Center
    • Tech Toolboxes
    • Webinars & Digital Events
  • Resources
    • Digital Issues
    • EE Training Days
    • LEAP Awards
    • Podcasts
    • Webinars / Digital Events
    • White Papers
    • Engineering Diversity & Inclusion
    • DesignFast
  • Guest Post Guidelines
  • Advertise
  • Subscribe