Site hosted by Angelfire.com: Build your free website today!

#include<stdio.h>

#include<sys/types.h>

#include<sys/socket.h>

#include<netinet/in.h>

#include<netdb.h>

#include<string.h>

#include<ctype.h>

 

#define PORT 6100

int sock;

struct sockaddr_in to;

 

/*the function that creates & fill the structure*/

void create_socket();

 

/*the function that implements the server*/

void Server();

 

/*the structure for the operands */

struct {

        int operand1;

        int operand2;

        } operands;

/*the structure for storing the results*/       

struct {

        int sum;

        int mult;

       } results;        

       

main()

{

create_socket();

Server();

}

 

void create_socket()

{

    int port;

    /*allocating memory for to*/

    bzero((char*)&to, sizeof(to));

    port = PORT;

    /*testing on the port number */

    if (port>0)

    to.sin_port =  htons((u_short)port);

    else exit(3);

    /*filling the structure to*/

    to.sin_family = AF_INET;

    to.sin_addr.s_addr = INADDR_ANY;

    /*creating the socket*/

    sock = socket(AF_INET,SOCK_DGRAM,0);

    if(sock < 0){

    perror("can not create the socket");

    exit(1);

     }

    /*bind the socket*/

    if(bind(sock,(struct sockaddr*)&to,sizeof(to))){

    perror("can not bind");

    exit(2);}

  }

        

void Server()

  {

    int recv,send;

    int length;

    struct sockaddr_in from;

   

    length = sizeof(from);

    /* infinite loop*/

    while(1)

       {

       /*allocating memory and receving the operands*/

        bzero((char *)&operands,sizeof(operands));

        recv= recvfrom(sock,(char*)&operands,8,0,(struct sockaddr *)&from,&length);

        if(recv<0) perror("error while receving");

       

        /*compute the results*/

        results.sum = operands.operand1 + operands.operand2;

        results.mult = operands.operand1*operands.operand2;

       

        /*send the results*/

        send=sendto(sock, (char*)&results,8, 0, (struct sockaddr *)&from,length);

        if(send<0) perror("error while sending");

      }

      

  }