Skip to main content

UDP Server-Client Communication in C++

This is sample code for UDP Server and Client Communication in C++.

Things to keep in mind :
  • First Run server and then client
  • If you receive error 10054 while running client, it is because of recvfrom() in client.cpp , as it is trying to receive from null reference. Either comment out recvfrom() or start server first.

//============================================================================
// Name        : Simple C++ UDP Server.cpp 
// Author      : Manish Kumar Khedawat
//============================================================================


#include "stdafx.h"
#include <iostream>
#include <winsock2.h>
#include<stdio.h>
#define BUFLEN 512
 
#pragma comment(lib,"ws2_32.lib") 
//Winsock Library, To Avoid Error in Visual Studio Compilation
using namespace std;


int main()
{
    WSAData version;        
 //WSAData is Structure which holds the information about windows socket implementation
    WORD mkword=MAKEWORD(2,2); 
 // MakeWord will return 2.2
    int what=WSAStartup(mkword,&version); 
 // Checking If you are on XP or Higher
    if(what!=0){
        std::cout<<"This version is not supported! - \n"<<WSAGetLastError()<<std::endl;
  exit(EXIT_FAILURE);
    }
    else{
        std::cout<<"Everything is fine!\n"<<std::endl; // Using XP+
    }

 // Creating Socket
 SOCKET server=socket(AF_INET,SOCK_DGRAM,0);  
 //  (specify to use ipv4, Using UDP Port, Internet Protocol default 0 )
    if(server==INVALID_SOCKET)
 {
        std::cout<<"Creating socket fail\n";
  exit(EXIT_FAILURE);
 }
    else
        std::cout<<"Socket was created :)\n";


 //Socket address information
    sockaddr_in ServerAddr;
 /*
 struct sockaddr_in {
        short   sin_family;
        u_short sin_port;
        struct  in_addr sin_addr;
        char    sin_zero[8];
  };
 */
    ServerAddr.sin_family=AF_INET; // ipv4 specification
    ServerAddr.sin_addr.s_addr=inet_addr("127.0.0.1"); //ipAddress to bind server
    ServerAddr.sin_port=htons(8080); // port to bind
    /*==========Addressing finished==========*/

    //Now we bind
    
    int conn=bind(server ,(struct sockaddr *)&ServerAddr , sizeof(ServerAddr));
    if(conn==SOCKET_ERROR){
        std::cout<<"Error - when connecting "<<WSAGetLastError()<<std::endl;
        closesocket(server);
        WSACleanup();
  exit(EXIT_FAILURE);
    }
 else
 {
  std::cout<<"Socket bind Successful at "
   << inet_ntoa(ServerAddr.sin_addr) 
   << ":"<<ntohs( ServerAddr.sin_port)<<std::endl;
 }

 while(1)
    {
        printf("Waiting for data...\n");
        fflush(stdout);
        char buf[BUFLEN]; 
        //clear the buffer by filling null, it might have previously received data
        memset(buf,'\0', BUFLEN);
  sockaddr_in  client;
  int recv_len,client_len=sizeof(client);
        //try to receive some data, this is a blocking call
        if ((recv_len = recvfrom(server, buf, BUFLEN, 0, (struct sockaddr *)&client, &client_len)) == SOCKET_ERROR)
        {
            printf("recvfrom() failed with error code : %d\n" , WSAGetLastError());
            exit(EXIT_FAILURE);
        }
         
        //print details of the client/peer and the data received
        printf("Received packet from client at %s\n", inet_ntoa(client.sin_addr));
        printf("Data: %s\n" , buf);
         
        //now reply the client with the same data
        if (sendto(server, buf, recv_len, 0, (struct sockaddr*) &client, client_len) == SOCKET_ERROR)
        {
            printf("sendto() failed with error code : %d" , WSAGetLastError());
            exit(EXIT_FAILURE);
        }
    }
 
    closesocket(server);
    WSACleanup();
    return 0;
}





//============================================================================
// Name        : Simple C++ UDPClient.cpp 
// Author      : Manish Kumar Khedawat
//============================================================================


#include "stdafx.h"
#include <iostream>
#include <winsock2.h>
#include<stdio.h>
 
#pragma comment(lib,"ws2_32.lib") 
//Winsock Library, To Avoid Error in Visual Studio Compilation
using namespace std;

#define SERVER "127.0.0.1"  //ip address of udp server
#define BUFLEN 512  //Max length of buffer
#define PORT 8080   //The port on which to listen for incoming data


int main()
{
 
 WSAData version;        
 //WSAData is Structure which holds the information about windows socket implementation
    WORD mkword=MAKEWORD(2,2); 
 // MakeWord will return 2.2
    int what=WSAStartup(mkword,&version); 
 // Checking If you are on XP or Higher
    if(what!=0){
        std::cout<<"This version is not supported! - \n"<<WSAGetLastError()<<std::endl;
  exit(EXIT_FAILURE);
    }
    else{
        std::cout<<"Everything is fine!\n"<<std::endl; // Using XP+
    }
 // Creating Socket
 SOCKET client=socket(AF_INET,SOCK_DGRAM,0);  
 //  (specify to use ipv4, Using UDP Port, Internet Protocol default 0 )
    if(client==INVALID_SOCKET)
 {
        std::cout<<"Creating socket fail\n";
  exit(EXIT_FAILURE);
 }
    else
        std::cout<<"Socket was created :)\n";

 //setup Server Address structure
 sockaddr_in server;
    memset((char *) &server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(PORT);
    server.sin_addr.S_un.S_addr = inet_addr(SERVER);

 //start communication
    while(1)
    {
  char message[BUFLEN],buf[BUFLEN];
  memset(message,'\0', BUFLEN);
        printf("Enter message : ");
        gets(message);
        int recv_len,server_len=sizeof(server);
        //send the message
        if (sendto(client, message, strlen(message) , 0 , (struct sockaddr *) &server, server_len) == SOCKET_ERROR)
        {
            printf("sendto() failed with error code : %d" , WSAGetLastError());
            exit(EXIT_FAILURE);
        }
         
        //receive a reply and print it
        //clear the buffer by filling null, it might have previously received data
        memset(buf,'\0', BUFLEN);
        //try to receive some data, this is a blocking call
        if (recvfrom(client, buf, BUFLEN, 0, (struct sockaddr *) &server, &server_len) == SOCKET_ERROR)
        {
            printf("recvfrom() failed with error code : %d" , WSAGetLastError());
            exit(EXIT_FAILURE);
        }
         
        puts(buf);
    }
 
    closesocket(client);
    WSACleanup();
 
    return 0;

 return 0;
}




Let me know through comments if it doesn't work out :)

Comments

Popular posts from this blog

Drawing and Animating ASCII Art in C# Console

This is sample code for drawing ASCII art character in C# console. Things to keep in mind : Replace the variable var with any ASCII art you want to get drawn in console.  Take care of [@],["] and [,] while replacing. using System ; namespace Dotned.UI.Framework { public class Arbit { public static void Main (String[] Args) { var arr = new [] { @" /$$$$$$ /$$ /$$ /$$ " , @" /$$__ $$ | $$ | $$ |__/ " , @" | $$ \__/ /$$$$$$ /$$$$$$/$$$$ /$$$$$$ /$$$$$$ | $$$$$$$ /$$ /$$$$$$$ /$$$$$$ " , @" | $$$$$$ /$$__ $$| $$_ $$_ $$ /$$__ $$|_ $$_/ | $$__ $$| $$| $$__ $$ /$$__ $$ " , @" ...

Git – setting up a remote repository and doing an initial push

So, Lets firstly set-up the remote repository: Step 1 : ssh will get me access to console on remote pc, will ask for remote pc's password Step 2 : create a directory with extension .git Step 3 : go to created directory Step 4 : initialize git Step 5 : Update Server configuration for access from non local sites Step 6 : Exit from remote access                     $ssh username@ipaddressofserverpc                    $mkdir my_project.git                    $cd my_project.git                    $git init --bare                    $git update-server-info # If planning to serve via HTTP                    $exit Now, On local machine: Step 1 : go to local folder Step 2 : Initia...

Serializing & Deserializing JSON Object [ C++ ]

         This is sample code for serializing an object into json object and deserializing it back into earlier object. Things to keep in mind : While creating a json object, you have to write  json_object* jObj=json_object_new_object();   initializing it as   json_object* jObj ;   will not work. You need to install JSON library using  $ sudo apt-get install libjson0 libjson0-dev, Check path of installed json here   $ ls /usr/include/json You need to add json library to linker or compiler path. For ex. in Eclipse , Right click on project >> properties >> path and symbols. Add /usr/include/json in library paths & json in libraries. //============================================================================ // Name : JsonTest.cpp // Author : Manish Kumar Khedawat //============================================================================ #include <iostream> #include <json...