//
// q1_server.c
//
//
// Question:
/*
Using sockets to write a server/client program as described below. The program does a very simple task. Here is what the program does.
a) The client connects to the server. Once successfully, it sends a simple Unix/Linux command. For simplicity, the command sent is a simple command without any command line arguments, such as ls, pwd, and ps, etc.
b) The server receives the command sent by the client, executes the command, and sends the output of the command back to the client. The client then displays the output. Hint: you could redirect the output of the server running the command to the connected socket to send the output from running the Linux command to the client.
Your program only needs to support one client. For simplicity, the client is only required to send one command. You could use any allowed port number. You could assume the output from the command is less than 40960 bytes.
*/
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
int main(int argc, char *argv[]){
char buffer[40960];
int sd, nsd;
socklen_t len;
int pid;
struct sockaddr_in servAdd;
struct sockaddr_in cliAdd;
servAdd.sin_family = AF_INET;
servAdd.sin_addr.s_addr = INADDR_ANY;
servAdd.sin_port = 7777;
sd = socket(AF_INET, SOCK_STREAM, 0);
bind(sd,(struct sockaddr*)&servAdd, sizeof(servAdd));
listen(sd, 5);
printf(“Waiting for a client…\n”);
len = sizeof(cliAdd);
nsd = accept(sd,(struct sockaddr*)&cliAdd, &len);
read(nsd, buffer, 40960);
printf(“command received: %s\n”, buffer);
dup2(nsd, 1);
close(nsd);
if((pid = fork())==-1){
perror(“fork”);
exit(1);
}
if(pid==0)
execlp(buffer, buffer, (char *)0);
else
wait(NULL);
return 0;
}