StatCounter

Monday, February 1, 2016

Socket Programming - Simple UDP client and server programs. ( In C)

UDP

UDP is a simple transport-layer protocol. The application writes a message to a UDP socket, which is then encapsulated in a UDP datagram, which is further encapsulated in an IP datagram, which is sent to the destination.  
There is no guarantee that a UDP will reach the destination, that the order of the datagrams will be preserved across the network or that datagrams arrive only once. 

Server
  1. Listen for a client's requests.
  2. Process the requests.
  3. Return the results back to the client. 

Client
  1. Send the request to the server.
  2. Wait for the server's response.
Server Program

[code]

#include <sys/socket.h>
#include <netinet/in.h>
#include <strings.h>
#include <stdio.h>

int main(int argc, char**argv)
{
    int sockfd,n;
    struct sockaddr_in servaddr, cliaddr;
    socklen_t len;
    char mes[1000];
    char send[] = "Hello client!";
   
    sockfd=socket(AF_INET,SOCK_DGRAM,0);
   
    servaddr.sin_family = AF_INET;   
    servaddr.sin_addr.s_addr=htonl(INADDR_ANY);
    servaddr.sin_port=htons(32000);
   
    bind(sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr));
    len = sizeof(cliaddr);
   
    while(1)
    {
        n=recvfrom(sockfd,mes,1000,0,(struct sockaddr*)&cliaddr,&len);
   
        sendto(sockfd,send,n,0,(struct sockaddr*)&cliaddr,sizeof(cliaddr));
        mes[n] = 0;
   
        printf("Client says: %s\n",mes);
    }   
    return 0;
}[/code]

Client Program

[code]

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


int main(int argc, char**argv)
{
    int sockfd,n;
    struct sockaddr_in servaddr;
    char send[] = "Hello server!";
    char recv[1000];

    if (argc != 2)
    {
        printf("usage:%s <IP address>\n",argv[0]);
        return -1;
    }
   
    sockfd=socket(AF_INET,SOCK_DGRAM,0);
    bzero(&servaddr,sizeof(servaddr));

    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr=inet_addr(argv[1]);
    servaddr.sin_port=htons(32000);

    sendto(sockfd,send,strlen(send),0,(struct sockaddr*)&servaddr,sizeof(servaddr));

    n=recvfrom(sockfd,recv,10000,0,NULL,NULL);

    recv[n]=0;
   
    printf("Server says: %s\n",recv);
    return 0;
}[/code]