Spread the love

Simulation of the Ethernet

This Simulation of the Ethernet C/C++ Project is used to simulate the Ethernet model explained in the class room. In this project, I was able to implement the interaction of Station-Process (SP) with the Communication Bus Process (CBP) through Socket programming. The SP is developed in C and the CBP is developed in C++. TCP is the transport protocol implemented for this project. In this project, when both SP and CBP are activated, any file sent on Station Process will be displayed on CBP.

Compile CBP file:

g++ -pthread cbp.cpp

Execute:

./a.out 7000 (we can use any port number instead of 7000 here)

Compiling SP file:

gcc stationprocess.c

Execute:

./a.out cbpname cbp_port-no file_requested

Eg: ./a.out cbp 7000 data.txt

To view output: vi slogfile

 

cbp.cpp file

 

#include<iostream>
#include<fstream.h> 
#include<iostream.h>
#include<sstream> 
#include<stdlib.h> 
#include<string.h> 
#include<sys/types.h> 
#include<sys/socket.h> 
#include<netinet/in.h> 
#include<sys/time.h> 
 
using namespace std; 
 
pthread_mutex_t slogfile_mutex = PTHREAD_MUTEX_INITIALIZER;
 
ofstream fout; 
 
void Accept_Connection(int );
void * Process_Request(void * );
void Writing_To_Logfile(std::string msg); 
 
int main(int argc,char* argv[])
{
      int server_port_number; 

      if(argc < 2)
      {
            cout<<"./a.out entered in a wrong way need to specify the port numberalong with ./a.out for ex: ./a.out 7000 "<<endl;
            return(0);
      } 
 
      server_port_number = atoi(argv[1]); 
 
      int server_sd=0;
      
      struct sockaddr_in server_addr;
 
      fout.open("slogfile"); 
 
      server_sd = socket(AF_INET,SOCK_STREAM,0); // Creating socket 
 
      if(server_sd<0)
      {
            printf("Cannot create socket");
            return 0;
      }
  
      cout<<"Socket created "<<server_sd<<endl; 
 
      server_addr.sin_family = AF_INET;

      server_addr.sin_addr.s_addr = INADDR_ANY;
 
      server_addr.sin_port = htons(server_port_number); 
 
      if(bind(server_sd, (struct sockaddr *) &server_addr, sizeof(server_addr))<0) // Binding socket
      {
            cout<<"Cannot bind port "<<endl;
            return 0;
      } 
      else
      {
            cout<<"Socket binded "<<endl;
      }  
 
      if (listen(server_sd, 3) < 0)
      {
             cout<<"Error while listening, please try again "<<endl;
             return 0;
      } 
 
       while(1)
      {
            cout<<"Waiting for data on port....  "<<endl;
            Accept_Connection(server_sd); 
      } 
 
      fout.close(); 
} 
 
void Accept_Connection(int server_sd)
{
      int client_sd = 0;
      int client_len = 0;
      struct sockaddr_in client_addr;
      pthread_t * client_processing_thread; 
      client_len = sizeof(client_addr);
      client_sd = accept(server_sd, (struct sockaddr *) &client_addr,(socklen_t *) &client_len); 
      if(client_sd<0)
      {
            cout<<"Cannot accept connection "<<endl;
            return ;
      } 
      else
            cout<<"Connection accepted "<<endl; 
 
      cout<<"Accepting request "<<endl;
      client_processing_thread = new pthread_t;
      pthread_create(client_processing_thread,NULL,Process_Request,(void *)client_sd); 
} 
 
 
 
void * Process_Request(void * client)
{
      char buffer[1024];
      int BUFFER_SIZE = 1024;
      int client_sd = (int) client;
      int sending_file_length;
      int file_size;
      int elapsed_sec;
      int elapsed_usec;
      double elapsed_time;
      time_t start_time;
      timeval start_send, end_time;
      struct tm * timeinfo;
      bool file_found = true;
      string file_name;
      stringstream storing_data; 
 
      time (&start_time);
      timeinfo = localtime(&start_time); 
 
      ifstream fin; // file being transfered to the client  
      memset(buffer, '\0', BUFFER_SIZE); 
 
      if ((read(client_sd,buffer,BUFFER_SIZE)) < 0)
      {
             cout<<"Cannot read the message "<<endl;
             return 0;
      } 
      cout<<"File name received: "<<buffer<<endl;
      cout<<"Processing request"<<endl; 
 
      file_name = buffer;
      start_time = time(NULL);
      fin.open(buffer,ios::binary);
      if (!fin.is_open())
      {
            // Eventually this will have to be a write command that will send back to the client, that an error occured.
            fin.open("filenotfound.txt",ios::binary);
            file_found = false;
      } 
 
      fin.seekg (0, ios::end); // get length of file:
      sending_file_length = fin.tellg();
      file_size= sending_file_length;
      fin.seekg (0, ios::beg); 
 
      sleep(((rand() % 5) + 1));  
      gettimeofday(&start_send, NULL); 
 
      do
      {
            memset(buffer, '\0', BUFFER_SIZE);  // clear the buffer
            fin.read(buffer, BUFFER_SIZE); 
            if (sending_file_length > BUFFER_SIZE)
            {
                  sending_file_length = sending_file_length - BUFFER_SIZE;
                  if((write(client_sd, buffer, BUFFER_SIZE)) < 0)
                        cout<<"Error in sending the message "<<endl;
            } 
            else
            {
                  if((write(client_sd, buffer, sending_file_length)) < 0)
                        cout<<"Error in sending the message "<<endl;
            } 
      } while (!fin.eof()); 
 
      gettimeofday(&end_time, NULL);
      elapsed_sec = end_time.tv_sec - start_send.tv_sec;
      elapsed_usec = end_time.tv_usec - start_send.tv_usec; 
  
      if (elapsed_usec < 0)
      {
            elapsed_sec--;
            elapsed_usec +=1000000;
      } 
 
      elapsed_time = (double)elapsed_sec + (double)elapsed_usec/1000000.0; 
 
      if (file_found == true)
      {
            storing_data<<"File requested : "<<file_name<<"("<<(double)file_size/1000 << "KB) @ "<<asctime(timeinfo)<<file_name<<" transfered in "<<elapsed_time<<"seconds ";
      } 
      else
      {
            storing_data<<"File requested : "<<file_name<<" File not found ";
      } 
 
      pthread_mutex_lock(& slogfile_mutex);
      Writing_To_Logfile(storing_data.str());
      pthread_mutex_unlock(& slogfile_mutex); 
      close (client_sd);
      fin.close();
      pthread_exit(NULL); 
 } 

void Writing_To_Logfile(string msg)
{
      fout<<msg<<endl<<endl;
}

 

stationprocess.c file

 

// This is the station process application that will be used to send requests to the Communication bus Process. It takes 3 arguments, server IP or host, port, and the file requested.
 
// List of includes
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <string.h>
 
#define MAXBUF 1024
 
int main (int argc,char* argv[]) 
{
    char cServer[20];
    char cPort[6];
    char cFile [200];
    int nPort;
  
    if (argc < 4)
    {
	printf ("Usage: sp cbpname cbp_port-no file_requested \r\n");
        return(0);
    }
 
	//sprintf(cServer,"%s",argv[1]);
	sprintf(cPort,"%s",argv[2]);
	nPort = atoi(cPort);
	sprintf(cFile,"%s",argv[3]);
	
	struct sockaddr_in name;
        struct hostent *hent;
        int sd;
 
    // create a new socket to use for communication
    if ((sd = socket (AF_INET, SOCK_STREAM, 0)) < 0) 
	{
		perror("(cliConn): socket() error");
        exit (-1);
    }
    // Used to correctly fill in the server host
	if ((hent = gethostbyname (cServer)) == NULL)
		fprintf (stderr, "Host not found");
	else
		bcopy (hent->h_addr, &name.sin_addr, hent->h_length);
 
	name.sin_family = AF_INET;
    name.sin_port = htons (nPort); // notice the host to network conversion.
 
	// connect to the server
	if (connect (sd, (struct sockaddr *)&name, sizeof(name)) < 0) 
	{
		perror("(cliConn): connect() error");
		exit (-1);
	}
 
	// send the request to the server, the request is simple the file name passed to the client from command line
	write (sd, cFile, sizeof(cFile));
	char buffer[MAXBUF];
	int bytes_read = 0;
	int total_bytes_read = 0;
 
	// keep reading data from the server, until done.
	do 
	{
		memset(buffer,0,MAXBUF);
		bytes_read = read(sd, buffer, MAXBUF-1);
		if (bytes_read < 0)
			break;
		fprintf(stdout,"Read %d bytes that are [%s]\r\n",bytes_read,buffer);
		total_bytes_read += bytes_read;
	} while ( bytes_read > 0 );
 
	printf("Total Bytes Read = %d\r\n",total_bytes_read);
	close(sd);
 
	return 0;
}