Sunday, May 13, 2018

UDP Server-Client implementation in C

UDP Server-Client interaction




UDP SERVER

 
//Programme for UDP server

#include<stdio.h>
#include<string.h>
#include <sys/types.h>     
#include <sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<unistd.h>
#include<netdb.h>
#include<fcntl.h>
#define PORT_NUM 1500  //port number on which message will recieve and send
int main()
{
 int sock;      //variable for socket descriptor(server)
 int len;       //variable for initialize structure length
 char out_buf[100],in_buf[100];   //variable for input and output message initialize

 struct sockaddr_in server,client;
 
 sock=socket(AF_INET,SOCK_DGRAM,0);       //socket descripter for server(using ipv4)
 server.sin_family=AF_INET;
 server.sin_port=htons(PORT_NUM);         //host to network short byte word
 server.sin_addr.s_addr=htonl(INADDR_ANY);//host to network long byte order
 len=sizeof(struct sockaddr_in);          //storing length of structure (define below)
 bind(sock,(struct sockaddr*)&server,len);//binding the socket with port num and ip

 printf("server is waiting.....\n");        //server goes to listen mode(explicitely define in tcp server)

 recvfrom(sock,in_buf,sizeof(in_buf),0,(struct sockaddr *)&client,&len);//recieve byte by byte stream from client 
                                                                        //at 'in_buf' through server socket 
 printf("request accepted.................\n");
 printf("recieve from client...message:=%s\n",in_buf);    //display message recieve from client
 strcpy(out_buf,"HI mr.client I have got your message"); //storing string at 'out_buf'
 sendto(sock,out_buf,(strlen(out_buf)+1),0,(struct sockaddr *)&client,len);//stream send to client through socket
            //(here length is increase by 1 because to assign null           //explicitely at the end of the stream 'out_buf')
 close(sock); 
}

  • SCREENSHOT------

UDP CLIENT

 
//programmme for udp client
#include<stdio.h>
#include<string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<unistd.h>
#include<netdb.h>
#include<fcntl.h>
#define PORT_NUM 1500  //port number on which message will recieve and send
#define SERVER_IP "127.127.127.127"//loop back address as i am using same system for botth server and client

int main()
{
 int sock;  //variable for socket descriptor(client)
 int len;   //variable for initialize structure length
 char out_buf[100],in_buf[100];  //variable for input and output message initialize
 
 struct sockaddr_in server;        //server address is required by client but viceversa is not needed
 sock=socket(AF_INET,SOCK_DGRAM,0);//socket descripter for server(using ipv4)
 server.sin_family=AF_INET;
 server.sin_port=htons(PORT_NUM);  //host to network short byte word
 server.sin_addr.s_addr=inet_addr(SERVER_IP);//function 'inet_addr()' converts  the Internet host address cp from
                                                    // IPv4 numbers-and-dots notation into binary data in network byte  order.

 len=sizeof(struct sockaddr_in);    //storing length of structure (define below)
 strcpy(out_buf,"hey server i am connecting with you..");//storing stream at out_buf for sending to server
 sendto(sock,out_buf,(strlen(out_buf)+1),0,(struct sockaddr *)&server,len);//stream send to client through socket
                                                                                   //(here length is increase by 1 because to assign null 
             //explicitely at the end of the stream 'out_buf')

 recvfrom(sock,in_buf,sizeof(in_buf),0,(struct sockaddr *)&server,&len);  //recieve byte by byte stream from client 
            //at 'in_buf' through server socket
 printf("recieve from server message:=%s\n",in_buf);
 close(sock);


}

 
  • SCREENSHOT--------
 
  • Explanation of different functions and structure 

    1. Data structure used to hold address information

      • struct sockaddr{
      unsigned short sa_family;
      char sa_data[14];
      sa_family is the domain type ex-
      AF_UNIX, AF_LOCAL   Local communication           
      AF_INET                       IPv4 Internet protocols         
      AF_INET6                     IPv6 Internet protocols         
      AF_IPX                          IPX - Novell protocols
      AF_NETLINK                Kernel user interface device

      • struct sockaddr_in{
      short sin_family;
      unsigned short sin_port;
      struct in_addr sin_addr;
      char sin_zero[8]; 
      }  
      sin_family is same as above sa_family i,e domain type ex- 
      AF_UNIX, AF_LOCAL   Local communication           
      AF_INET                       IPv4 Internet protocols         
      AF_INET6                     IPv6 Internet protocols         
      AF_IPX                          IPX - Novell protocols
      AF_NETLINK                Kernel user interface device
      sin_port---It is for assignning port number
      in_addr sin_addr----here in_addr is a structure whose variable is sin_addr,it is used for assigning ip address.
      sin_zero----It is used for padding

      • struct in_addr{
      unsigned long s_addr; //4 byte
      }
      s_addr---- it is used for storing 4 byte IP address(32 bit IP
    2. socket() - A Connection End point

      • This creates an end point for network connection.
       int socket(int domain,int type,int protocol)
      domin=AF_INET(ipv4 protocol)
      type=   SOCK_STREAM(TCP), SOCK_DGRAM(UDP)
      protocol=0
      • Eample :=socket(AF_INET,SOCK_STREAM,0)
      this will create a TCP socket
      • This al returns 1 ,when socket descriptor on success and -1 on an error
       
    3. bind() - Attaching to an IP and Port 

      • Aserver call bind to attach itself to a specific port and IP address
      int bind(int sockfd, const struct sockaddr *my_address, socklen_t address_length);
      my_addr=pointer to a valid sockaddr_in structure cast as a sockaddr *pointer
      addrlen=lngth of the sockaddr_in structur 
    4. listen() - wait for a connection

      • The serverprocess calls listen to tell the kernal to initialize a wait queueof connection for this socket

      listen(int sock, int backlog); 

      sock=socket returned by socket()
      backlog=maximum length of the pending connections queue

      • Example:listen(sock,10);
      This will allow a maximum of 10 connections to be in pending state
  • Accept() - A new connection! 

           > Accept is called by a Server process to accept new connections from      new clients trying to connect to the server

accept(int soccket, (struct sockaddr *)&client, socklen_t *client_len) 

socket= the socket in listen state
client=will hold new clients information when accept returns
client_len=pointer to size of the client structure

>Example:
struct sockaddr_in client;
int len=sizeof(client);
accept(sock, (struct sockaddr *)&client, &len); 

  • connect() - connect to a service

    >Connect is automatically called by a client to connect to a serverport

    conect(int sock, (struct sockaddr *)&server_addr, socklen_t len)

    sock : a socket returned by socket()
    server_addr : a sockaddr_in struct pointer filled with all the remote server detailes and cast as a sockaddr struct pointer
    len : size of the server_addr struct

    >Example:
    connect(sock, (struct sockaddr *)&server_addr, len); 
    • Send/Recv - Finally Data !!

      > send(),recv(),read(),write() etc calls are used to send or recieve data
      int send(int sock, void *mesg, size_t len,int flag)
      int recv(int sock, void *mesg, size_t len, int flag)

      sock=Aconnected socket
      mesg=pointer to a buffered to send /recieve data from/in
      len=size of the message buffer
      flags=0

      The return value is the number of bytes actually sent/recieved

      >EXAMPLE:

      char send_buffer[1024];
      char recv_buffer[1024];
      int sent_bytes;
      int recv_bytes;

      sent_bytes=send(sock,send_buffer,1024,0);
      recv_bytes=recv(sock, recv buffer,1024,0);

      • close) - T termiate the connection

        >close() =This signal indicates the end of the communication between server &c lient, this also closes the socket

        close(int sock)

        sock=the socketto close

        >EXAMPLE:close(sock);
       

                 

1 comment:

Fibonacci Series Using Dynamic Programming in C++

Fibonacci Series Using Dynamic Programming #include<iostream> #include<vector> using namespace std; int fibo(in...