UDP/IP Protocol in Half Duplex Mode using C/C++

by Angelos on November 14, 2009

UDP/IP is a famous protocol used for voice and video communication. It is easy to implement as compared to TCP/IP protocol as it doesn’t require handshaking signals for establishing communication. But it can loose data packets as you have no way to know if all the data packets have reached the destination. Code for UDP/IP protocol implemented in C/C++ working in half duplex mode is given below.

UDP/IP Sender

#include
#include

#define APP_PORT                4020
#define REMOTE_SYSTEM   "192.168.1.113"

void main()
{
        WSADATA w;
        WSAStartup(0×0202,&w);

        SOCKET sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if(sockfd == INVALID_SOCKET)
        {
       printf("socket creation failed\n");
           return;
        }

        sockaddr_in to;
        to.sin_family= AF_INET;
        to.sin_addr.s_addr = inet_addr(REMOTE_SYSTEM);
        to.sin_port= htons(APP_PORT);

        char buffer[7] = "hello!";

        int nRet=0;
        while(1)
        {
                nRet = sendto(sockfd, buffer, 7, 0, (sockaddr*)&to, sizeof(sockaddr));
                if(nRet == SOCKET_ERROR )
                {
                        printf("Data sent failed\n");
                }
                printf("%d bytes sent on ip %s and port %d\n", nRet, REMOTE_SYSTEM, APP_PORT);
                Sleep(1000);
        }
}

UDP/IP Receiver

#include
#include

#define APP_PORT                4020
#define LOCAL_IP                "192.168.1.113"

void main()
{
        WSADATA w;
        WSAStartup(0×0202,&w);

        SOCKET sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if(sockfd == INVALID_SOCKET)
        {
       printf("socket creation failed\n");
           return;
        }

        int nRet=0;
        sockaddr_in local;
        local.sin_family= AF_INET;
        local.sin_addr.s_addr = inet_addr(LOCAL_IP);
        local.sin_port= htons(APP_PORT);

        nRet = bind(sockfd, (sockaddr*)&local, sizeof(sockaddr));
        if(nRet == SOCKET_ERROR)
        {
                printf("failed to bind socket %d to ip %s and port %d\n", sockfd, LOCAL_IP, APP_PORT);
                return;
        }

        char buffer[200];
        sockaddr_in from;
        int nSize= sizeof(from);

        while(1)
        {
                nRet = recvfrom(sockfd, buffer, 200, 0, (sockaddr*)&from, &nSize);
                if(nRet == SOCKET_ERROR )
                {
                        printf("Data failed failed\n");
                        return;
                }
                printf("%d bytes data recieved from ip %s and port %d\n", nRet, inet_ntoa(from.sin_addr),

ntohs(from.sin_port));
        }
}

Related Posts

  1. TCP/IP Protocol in Half Duplex Mode using C/C++
  2. Creating & Recording Sound in WAV file using MIMOS with C/C++
blog comments powered by Disqus

Previous post:

Next post: