C Linux Code for Server Handling multiple Clients Simueltaneously

//-----------CONCURRENT_CHAT_FORK--------//
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>//for sockaddr_in
#include <string.h>
#include <unistd.h>

#define MAXLINE 4096 /*max text line length*/
#define SERV_PORT 3000 /*port*/
#define LISTENQ 8 /*maximum number of client connections*/

int main (int argc, char **argv)
{
 int listenfd, connfd, n;
 pid_t childpid;
 socklen_t clilen;
 char buf[MAXLINE];
 struct sockaddr_in cliaddr, servaddr;

 //Create a socket for the soclet
 //If sockfd<0 there was an error in the creation of the socket
 if ((listenfd = socket (AF_INET, SOCK_STREAM, 0)) <0) {
  perror("Problem in creating the socket");
  exit(2);
 }


 //preparation of the socket address
 servaddr.sin_family = AF_INET;
 servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
 servaddr.sin_port = htons(SERV_PORT);

 //bind the socket
 bind (listenfd, (struct sockaddr *) &servaddr, sizeof(servaddr));

 //listen to the socket by creating a connection queue, then wait for clients
 listen (listenfd, LISTENQ);

 printf("%s\n","Server running...waiting for connections.");

 for ( ; ; ) {

  clilen = sizeof(cliaddr);
  //accept a connection
  connfd = accept (listenfd, (struct sockaddr *) &cliaddr, &clilen);

  printf("%s\n","Received request...");

  if ( (childpid = fork ()) == 0 ) {//if it’s 0, it’s child process

  printf ("%s\n","Child created for dealing with client requests");

  //close listening socket
  close (listenfd);

  while ( (n = recv(connfd, buf, MAXLINE,0)) > 0)  {
   printf("%s","String received from and resent to the client:");
   puts(buf);
   send(connfd, buf, n, 0);
  }

  if (n < 0)
   printf("%s\n", "Read error");
  exit(0);
 }
 //close socket of the server
 close(connfd);
}
}

//----------CLIENT_CONCUURENT_FORK------//
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <arpa/inet.h>

#define MAXLINE 4096 /*max text line length*/
#define SERV_PORT 3000 /*port*/

int main(int argc, char **argv)
{
 int sockfd;
 struct sockaddr_in servaddr;
 char sendline[MAXLINE], recvline[MAXLINE];

 //basic check of the arguments
 //additional checks can be inserted
 if (argc !=2) {
  perror("Usage: TCPClient <IP address of the server");
  exit(1);
 }

 //Create a socket for the client
 //If sockfd<0 there was an error in the creation of the socket
 if ((sockfd = socket (AF_INET, SOCK_STREAM, 0)) <0) {
  perror("Problem in creating the socket");
  exit(2);
 }

 //Creation of the socket
 memset(&servaddr, 0, sizeof(servaddr));
 servaddr.sin_family = AF_INET;
 servaddr.sin_addr.s_addr= inet_addr(argv[1]);
 servaddr.sin_port =  htons(SERV_PORT); //convert to big-endian order

 //Connection of the client to the socket
 if (connect(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr))<0) {
  perror("Problem in connecting to the server");
  exit(3);
 }

 while (fgets(sendline, MAXLINE, stdin) != NULL) {

  send(sockfd, sendline, strlen(sendline), 0);

  if (recv(sockfd, recvline, MAXLINE,0) == 0){
   //error: server terminated prematurely
   perror("The server terminated prematurely");
   exit(4);
  }
  printf("%s", "String received from the server: ");
  fputs(recvline, stdout);
 }

 exit(0);
}

C Linux Code for multi threaded socket chat

//server_threaded_chat_concurrent
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>//for sockaddr_in
#include <string.h>
#include <unistd.h>

#define MAXLINE 4096 /*max text line length*/
#define SERV_PORT 3000 /*port*/
#define LISTENQ 8 /*maximum number of client connections*/


char buf[MAXLINE];
int n;
void do_service(int sd)
{
while ( (n = recv(sd, buf, MAXLINE,0)) > 0)  {
   printf("%s","String received from and resent to the client:");
   puts(buf);
   send(sd, buf, n, 0);
  }

  if (n < 0){
   printf("%s\n", "Read error");
  exit(0);
}
}


//do service function executed by child
int  curr_sd, n;
void* body(int *arg)
{
struct sockaddr_in c_add;
int addrlen;
int i,l;
int base_sd = (int) arg;
int sd;
while (1) {
//pthread_mutex_lock(&m_acc);
sd = accept(base_sd, &c_add, &addrlen);
//pthread_mutex_unlock(&m_acc);
printf("\n\nsd=%d\n\n",sd);
do_service(sd);
close(sd);
/*curr_sd=sd;
while ( (n = recv(curr_sd, buf, MAXLINE,0)) > 0)  {
   printf("%s","String received from and resent to the client:");
   puts(buf);
   send(curr_sd, buf, n, 0);
  }

  if (n < 0){
   printf("%s\n", "Read error");
  exit(0);
 }*/
}
}

//creating socket and listening
int connectbody()
{
int base_sd2;
struct sockaddr_in c_add, servaddr;

 if ((base_sd2 = socket (AF_INET, SOCK_STREAM, 0)) <0) {
  perror("Problem in creating the socket");
  exit(2);
 }

 //preparation of the socket address
 servaddr.sin_family = AF_INET;
 servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
 servaddr.sin_port = htons(SERV_PORT);

 //bind the socket
 bind (base_sd2, (struct sockaddr *) &servaddr, sizeof(servaddr));

 //listen to the socket by creating a connection queue, then wait for clients
 listen (base_sd2, LISTENQ);

 printf("%s\n","Server running...waiting for connections.");

return base_sd2;
}

int main (int argc, char **argv)
{

 //Create a socket and listen

int base_sd;
base_sd=connectbody();

//accepting the maximum queud connections
pthread_t t[10];
struct sockaddr_in c_add;
socklen_t addrlen;
addrlen = sizeof(c_add);
int i;
for (i=0 ;i<10 ;i++ )
{
  printf("\n\nthread is t[%d]\n\n",i);
 // curr_sd = accept (base_sd, (struct sockaddr *) &c_add, &addrlen );
  //body(curr_sd);
pthread_create(&t[i],0,body,(void *)base_sd);
}//end of infinite for loop
pause();
//close(base_sd);
}
////////////---------------------CLIENT--------------------///////////////////
//client_threaded_chat_concurrent
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <arpa/inet.h>

#define MAXLINE 4096 /*max text line length*/
#define SERV_PORT 3000 /*port*/

int
main(int argc, char **argv)
{
 int sockfd;
 struct sockaddr_in servaddr;
 char sendline[MAXLINE], recvline[MAXLINE];

 //basic check of the arguments
 //additional checks can be inserted
 if (argc !=2) {
  perror("Usage: TCPClient <IP address of the server");
  exit(1);
 }

 //Create a socket for the client
 //If sockfd<0 there was an error in the creation of the socket
 if ((sockfd = socket (AF_INET, SOCK_STREAM, 0)) <0) {
  perror("Problem in creating the socket");
  exit(2);
 }

 //Creation of the socket
 memset(&servaddr, 0, sizeof(servaddr));
 servaddr.sin_family = AF_INET;
 servaddr.sin_addr.s_addr= inet_addr(argv[1]);
 servaddr.sin_port =  htons(SERV_PORT); //convert to big-endian order

 //Connection of the client to the socket
 if (connect(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr))<0) {
  perror("Problem in connecting to the server");
  exit(3);
 }

 while (fgets(sendline, MAXLINE, stdin) != NULL) {

  send(sockfd, sendline, strlen(sendline), 0);

  if (recv(sockfd, recvline, MAXLINE,0) == 0){
   //error: server terminated prematurely
   perror("The server terminated prematurely");
   exit(4);
  }
  printf("%s", "String received from the server: ");
  fputs(recvline, stdout);
 }
//close(sockfd);
 exit(0);
}

                                               

C Linux Code for multi threaded socket client/Server file sharing ftp

C Linux Code for:
1.Client sends a file name request
2.Server replies with the content if file exists
3.Server saves the file contenet received
/*----------server.c------------------*/
/*multi threaded concurrent server receiving file name request and sends the content if file exists*/
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>//for sockaddr_in
#include <string.h>
#include <unistd.h>

#define MAXLINE 4096 /*max text line length*/
#define SERV_PORT 3000 /*port*/
#define LISTENQ 8 /*maximum number of client connections*/


char buf[MAXLINE];
int n;
void do_service(int sd2)
{
/*while ( (n = recv(p, buf, MAXLINE,0)) > 0)  {
   printf("%s","String received from and resent to the client:");
   puts(buf);
   send(p, buf, n, 0);
  }

  if (n < 0){
   printf("%s\n", "Read error");
  exit(0);
}*/
int alen; /* length of address */
char buf_recv[1000],buf_send[1000]; /* buffer for string the server send 1000 */
char file_buffer[10000],f_buffer[1000];
int n;
FILE *fp;
printf("\n\nRequesting client to send file name:\n\n");
sprintf(buf_send,"Please enter the file name: ");
send(sd2,buf_send,strlen(buf_send),0);


printf("\n\nReceiving the file name:\n\n");
n=recv(sd2,buf_recv,1000,0);
buf_recv[n]='\0';
printf("%s\n",buf_recv);
fflush(stdout);


printf("Checking FILE:%s exists or not...\n",buf_recv);
if((fp = fopen(buf_recv,"r"))==NULL)
{
sprintf(buf_send,"File could not be found!!!");
exit(0);
}
else
{
printf("\nFile found!!!\n");
sprintf(buf_send,"File found!!!\n");
send(sd2,buf_send,strlen(buf_send),0);
}


        printf("Sending the file content to client....\n");
while(!feof(fp))//loops till eof
{
fgets(f_buffer,1000,fp);//extracts 1000 chars from file
if (feof(fp))
break;
strcat(file_buffer,f_buffer);
}
fclose(fp);
send(sd2,file_buffer,strlen(file_buffer),0);//sends 1000 extracted byte
close(sd2);
printf("[Server] Connection with Client closed. Server will wait now...\n");
}//end of do_service


//do service function executed by child
int  curr_sd, n;
void* body(int *arg)
{
struct sockaddr_in c_add;
int addrlen;
int i,l;
int base_sd = (int) arg;
int sd;
while (1) {
//pthread_mutex_lock(&m_acc);
sd = accept(base_sd, &c_add, &addrlen);
//pthread_mutex_unlock(&m_acc);
printf("\n\nserver connected now sd=%d\n\n",sd);
do_service(sd);
close(sd);
}
}

//creating socket and listening
int connectbody()
{
int base_sd2;
struct sockaddr_in c_add, servaddr;

 if ((base_sd2 = socket (AF_INET, SOCK_STREAM, 0)) <0) {
  perror("Problem in creating the socket");
  exit(2);
 }

 //preparation of the socket address
 servaddr.sin_family = AF_INET;
 servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
 servaddr.sin_port = htons(SERV_PORT);

 //bind the socket
 bind (base_sd2, (struct sockaddr *) &servaddr, sizeof(servaddr));

 //listen to the socket by creating a connection queue, then wait for clients
 listen (base_sd2, LISTENQ);

 printf("%s\n","Server running...waiting for connections.");

return base_sd2;
}

int main (int argc, char **argv)
{

 //Create a socket and listen

int base_sd;
base_sd=connectbody();

//accepting the maximum queud connections
pthread_t t[10];
struct sockaddr_in c_add;
socklen_t addrlen;
addrlen = sizeof(c_add);
int i;
for (i=0 ;i<10 ;i++ )
{
printf("\n\nthread id=t[%d]\n\n\n\n\n",i);
printf ("%s\n","thread created for dealing with client requests");
pthread_create(&t[i],0,body,(void *)base_sd);
pause();
}//end of infinite for loop
}
                                               
//---------------------------client.c----------------------
//client thread receiving file
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <arpa/inet.h>

#define MAXLINE 4096 /*max text line length*/
#define SERV_PORT 3000 /*port*/

int main(int argc, char **argv)
{
 int sd;
 struct sockaddr_in servaddr;
 char sendline[MAXLINE], recvline[MAXLINE];

 //basic check of the arguments
 //additional checks can be inserted
 if (argc !=2) {
  perror("Usage: TCPClient <IP address of the server");
  exit(1);
 }

 //Create a socket for the client
 //If sd<0 there was an error in the creation of the socket
 if ((sd = socket (AF_INET, SOCK_STREAM, 0)) <0) {
  perror("Problem in creating the socket");
  exit(2);
 }

 //Creation of the socket
 memset(&servaddr, 0, sizeof(servaddr));
 servaddr.sin_family = AF_INET;
 servaddr.sin_addr.s_addr= inet_addr(argv[1]);
 servaddr.sin_port =  htons(SERV_PORT); //convert to big-endian order

 //Connection of the client to the socket
 if (connect(sd, (struct sockaddr *) &servaddr, sizeof(servaddr))<0) {
  perror("Problem in connecting to the server");
  exit(3);
 }
else
printf("\nconnected to server now.\n");
/*file start*/

int n;
char buf_recv[1000];
char buf_send[1000];
char *filename;
char file_buffer[1000];
FILE *fp;
//code for receivind statement "Enter the file name"
n = recv(sd, buf_recv, sizeof(buf_recv), 0);
buf_recv[n]='\0';
printf("%s",buf_recv);


printf("\n\nNow sending the file name: \n\n");
scanf("%s",buf_send);
send(sd,buf_send,strlen(buf_send),0);


printf("\n\n receiving the string \"File found or not\"\n\n");
n = recv(sd, buf_recv, sizeof(buf_recv), 0);
buf_recv[n]='\0';
printf("%s",buf_recv);
fflush(stdout);


printf("\n\n Receiving the file content \n\n");
n=recv(sd, file_buffer, sizeof(file_buffer), 0);
file_buffer[n]='\0';
fflush(stdout);

fp = fopen("received_file.txt","w");
fputs(file_buffer,fp);
fclose(fp);
close(sd);

return 0;
}
//---------------------------OUTPUT......................
SERVER RUN:
=============
-bash-3.2$ gcc server_thread_file_conc.c -o ser -lpthread

-bash-3.2$ ./ser
Server running...waiting for connections.

thread id=t[0]

thread created for dealing with client requests

server connected now sd=4

Requesting client to send file name:

Receiving the file name:
-------
input.txt
Checking FILE:input.txt exists or not...

File found!!!
Sending the file content to client....
[Server] Connection with Client closed. Server will wait now...

server connected now sd=4

Requesting client to send file name:

Receiving the file name:
----------

CLIENT1 RUN:
================
-bash-3.2$ gcc client_thread_file_conc.c -o c1
-bash-3.2$ ./c1 127.0.0.1

connected to server now.
Please enter the file name:

Now sending the file name:
----------

input.txt

receiving the string "File found or not"

File found!!!

Receiving the file content


CLIENT2 RUN:
==========================
-bash-3.2$ gcc client_thread_file_conc.c -o c2
-bash-3.2$ ./c2 127.0.0.1

connected to server now.
--------------
input2.txt


receiving the string "File found or not"

File found!!!
c linuc code 

input2 input2 input2
input2 input2 input2
input2 input2 input2
input2 input2 input2
input2 input2 input2
input2 input2 input2


Receiving the file content

-bash-3.2$

C Linux Code for grepping pattern and replacing with other word

/* C Linux Code for counting  the repeated words in a file and replace it with another word*/
#include<stdio.h>
#include<string.h>

void repeatCount();

int main()
{
repeatCount();
return 0;
}

void repeatCount()
{
FILE *fp,*fp2;
fp=fopen("m1.txt","r");
fp2=fopen("m2.txt","w");
char ch;
char str_rep[20];
char str_temp[20];
char str_new[20];
int count=0;
int wordcount=0;

printf("Enter word to look for repeat:\n");
scanf("%s",str_rep);
printf("Enter word to replace wirh:\n");
scanf("%s",str_new);

while((ch=getc(fp))!=EOF)
{
//printf("\ninside while\n");
if(ch==' ')
{
// printf("inside ch=\n");
str_temp[count]='\0';

if(strcmp(str_temp,str_rep)==0)
{
//printf("inside strcmp\n");
wordcount++;
fprintf(fp2," %s",str_new);
count=0;
}
else
{
//printf("inside else of strcmp\n");
fprintf(fp2," %s",str_temp);
count=0;}
}//if(ch=' ') ends
else// else of ch=' '
{
str_temp[count++]=ch;
}

}//while endsi

printf("The word %s repeats %d times.\n",str_rep,wordcount);

fclose(fp);
fclose(fp2);
fflush(stdin);
}//repeatCount ends

C Linux Code for replacing a word with another word in a file

/*C Linux Code  to count repeated word and replace it with another word*/
#include<stdio.h>
#include<stdlib.h>

void count_data();

int main()
{
   // calling function
   count_data();
return 0;
}
void count_data() // function for count no of words,lines & characters.
{
   FILE *fp,*fp_rep;
   char ch,ch1,temp_str[50],rep_str[10],new_str[10];
   int count=0; // counter


   fp=fopen("m1.txt","r");
   fp_rep=fopen("m2.txt","w");

   printf("\nEnter String to find:");
   scanf("%s",rep_str);
   printf("\nEnter String to replace:");
   scanf("%s",new_str);
int wordcount=0;
   while((ch=getc(fp))!=EOF)
   {
     if(ch==' ')
      {
    temp_str[count]='\0';
    if(strcmp(temp_str,rep_str)==0)
     {
      wordcount++;
      printf("Replacing):");
      //ch1=getchar();
      //if(ch1=='y')
      //{
       fprintf(fp_rep," %s",new_str);
       count=0;
     // }
     // else
       //{ fprintf(fp_rep," %s",temp_str);count=0;}
     }
    else
     {
       fprintf(fp_rep," %s",temp_str);
       count=0;
      }
      }else
      {
    temp_str[count++]=ch;
      }
    }
printf("Total number of %s repeated=%d\n",rep_str,wordcount);
     /* if(strcmp(temp_str,rep_str)==0)
     {

      printf("Do u want to replace(y/n):");
      ch1=getchar();
      if(ch1=='y')
      {
       fprintf(fp_rep,"%s ",new_str);
       count=0;
      }
      else
       {
        fprintf(fp_rep,"%s ",temp_str);
        count=0;
       }
     }else
      {
       fprintf(fp_rep,"%s ",temp_str);
      }*/

    fclose(fp);
    fclose(fp_rep);
    //remove("m1.txt");
    //rename("m2.txt","m1.txt");
    fflush(stdin);
}

C Linux Code to count number of times given word repeated in a file

/*C Linux Code for Counting the given word in given text file*/
#include<stdio.h>
#include<string.h>

void repeatCount();

int main()
{
repeatCount();
return 0;
}

void repeatCount()
{
FILE *fp;
fp=fopen("m1.txt","r");
char ch;
char str_rep[20];

char str_temp[20];
int count=0;
int wordcount=0;

printf("Enter word to look for repeat:\n");
scanf("%s",str_rep);

while((ch=getc(fp))!=EOF)
{
//printf("\ninside while\n");
if(ch==' ')
{
// printf("inside ch=\n");
str_temp[count]='\0';

if(strcmp(str_temp,str_rep)==0)
{
//printf("inside strcmp\n");
wordcount++;
count=0;
}
else
{
//printf("inside else of strcmp\n");
count=0;}
}//if(ch=' ') ends
else// else of ch=' '
{
str_temp[count++]=ch;
}

}//while endsi

printf("The word %s repeats %d times.\n",str_rep,wordcount);

fclose(fp);
fflush(stdin);
}//repeatCount ends