You are on page 1of 54

IT 308

Computer Network File

Made by:
Name: Pulkit Aggarwal
Roll No: 755/IT/12
NSIT,Delhi

Q1)

a) Create and handle Processes in Linux operating system. Make use of fork, sleep, wait, exit,
getpid, getppid system calls and ps, kill Linux commands.
#include<stdio.h>
#include<sys/types.h> // For pid_t data type
#include<unistd.h> // For getpid(),etc
int main(void)
{
printf("Main Program ID : %d\n",(int)getpid());
pid_t child_pid = fork();
if(child_pid != 0)
{
printf("This is the parent process with ID %d\n",(int)getpid());
sleep(5);
printf("The child's process ID is %d\n",(int)child_pid);
}
else
printf("This is the child process with ID %d\n",(int)getpid());
return 0;
}

b) Design and implement a simple, interactive shell program that prompts the user for a command,
parses the command, and then executes it with a child process by looking at PATH environment
variable.
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h> // For pid_t data type
#include<string.h>

#define MAX 50

int ExecuteCommand(char **args)


{
pid_t pid = fork(), status;
if (pid < 0) // pid cannot be negative
{
fprintf(stderr,"Pid cannot be negative\n");
exit(1);
}
else if (pid == 0) // Child Process
{
execvp(*args, args);
perror(*args);
abort ();
}
else
{
//wait(&status);
}
}
void CreateList(char *A,char **Arg)
{
while(*A != '\0')
{
while((*A == ' ') || (*A == '\t'))
{
*A = '\0';
A++;
}
*Arg = A;

Arg++;
while((*A) && (*A != ' ') && (*A != '\t'))
A++;
}
*Arg = '\0';
}
int main(void)
{
char A[MAX];
char *Arg[MAX];
while(1)
{
printf("My Shell : ");
gets(A);
//if(strstr
CreateList(A,Arg);
ExecuteCommand(Arg);
}
return 0;
}

Q2)
a) Write a simple conversational program in C using sockets. The program should be possible to start as
client or as server. The server should notify about a call from the client's host, by giving its name, and
prompt for reply. After that a half-duplex conversation will begin, both ends display received messages
and prompt for reply. The conversation ends by a host sending a "close" message.

Client
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#define PORT "3490" // the port client will be connecting to
#define MAXDATASIZE 100 // max number of bytes we can get at once
// get sockaddr, IPv4 or IPv6:
void *get_in_addr(struct sockaddr *sa)
{
if (sa->sa_family == AF_INET) {
return &(((struct sockaddr_in*)sa)->sin_addr);
}
return &(((struct sockaddr_in6*)sa)->sin6_addr);
}
int main(int argc, char *argv[])
{
int sockfd, numbytes;
char buf[MAXDATASIZE];
struct addrinfo hints, *servinfo, *p;
int rv;
char s[INET6_ADDRSTRLEN];
if (argc != 2) {
fprintf(stderr,"usage: client hostname\n");
exit(1);
}
memset(&hints, 0, sizeof hints);

hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;

if ((rv = getaddrinfo(argv[1], PORT, &hints, &servinfo)) != 0)


{
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
return 1;
}
for(p = servinfo; p != NULL; p = p->ai_next)
{
if ((sockfd = socket(p->ai_family, p->ai_socktype,p->ai_protocol)) == -1)
{
perror("client: socket");
continue;
}
if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1)
{
close(sockfd);
perror("client: connect");
continue;
}
break;
}
if (p == NULL)
{
fprintf(stderr, "client: failed to connect\n");
return 2;
}
inet_ntop(p->ai_family, get_in_addr((struct sockaddr *)p->ai_addr),s, sizeof s);

printf("client: connecting to %s\n", s);


freeaddrinfo(servinfo); // all done with this structure
char Msg[100];
while(1)
{

printf("Enter message to be sent to server : ");


gets(Msg);
send(sockfd, Msg, strlen(Msg), 0);
if(strcmp(Msg,"close") == 0)
return 0;
start :
numbytes = recv(sockfd, buf, MAXDATASIZE-1, 0);
buf[numbytes] = '\0';
if(!buf[0])
goto start;
printf("client received : %s\n",buf);
}
close(sockfd);
return 0;

Server
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h> //for perror
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

#include <netdb.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <signal.h>
#define PORT "3490" // the port users will be connecting to
#define BACKLOG 10

// how many pending connections queue will hold

void *get_in_addr(struct sockaddr *sa)


{
if (sa->sa_family == AF_INET) {
return &(((struct sockaddr_in*)sa)->sin_addr);
}
return &(((struct sockaddr_in6*)sa)->sin6_addr);
}
int main(void)
{
int sockfd, new_fd,rv; // listen on sock_fd, new connection on new_fd
struct addrinfo hints, *servinfo, *p; //servinfo will point to hints
struct sockaddr_storage their_addr; // connector's address information
socklen_t sin_size;
char buf[100];
char s[INET6_ADDRSTRLEN]; //#define in netinet/in.h Value is 46.INET_ADDRSTRLEN 16
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC; //IP can be either IPv4 or IPv6
hints.ai_socktype = SOCK_STREAM; // Stream socket
hints.ai_flags = AI_PASSIVE; // use my IP.attach IP of host to structure

if ((rv = getaddrinfo(NULL, PORT, &hints, &servinfo)) != 0) //servinfo stores info of all IP associate with host
{
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));

return 1;
}
for(p = servinfo; p != NULL; p = p->ai_next)
{
if ((sockfd = socket(p->ai_family, p->ai_socktype,p->ai_protocol)) == -1)
perror("server: socket");
continue;
}
if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) //binding to the host
{
close(sockfd);
perror("server: bind");
continue;
}
break;
}
if (p == NULL)
{
fprintf(stderr, "server: failed to bind\n");
return 2;
}
freeaddrinfo(servinfo); // all done with this structure
if (listen(sockfd, BACKLOG) == -1)
{
perror("listen");
exit(1);
}

printf("server: waiting for connections...\n");

int num;
while(1)
{
sin_size = sizeof their_addr;
new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size);
if (new_fd == -1)
{
perror("accept");
continue;
}
inet_ntop(their_addr.ss_family,get_in_addr((struct sockaddr *)&their_addr),s, sizeof s);
char Msg[100];
printf("server: got connection from %s\n", s);
while(1)
{
num = recv(new_fd,buf,sizeof(buf),0);
buf[num] = '\0';
if(strcmp(buf,"close") == 0)
{
printf("Connection closed\n");
return 0;
}
else
printf("Message received from client : %s\n",buf);
printf("Enter Message to be send: ");
gets(Msg);
send(new_fd, Msg, sizeof(Msg), 0);

close(new_fd); // parent doesn't need this


}
return 0;
}

b) Write simple Server and Client programs using the socket programming on Linux (UNIX) that can
simulate the functionality of a real FTP Server and Client.

FTP Client
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#define PORT "3490" // the port client will be connecting to
#define MAXDATASIZE 100 // max number of bytes we can get at once
void *get_in_addr(struct sockaddr *sa)
{
if (sa->sa_family == AF_INET) {
return &(((struct sockaddr_in*)sa)->sin_addr);
}
return &(((struct sockaddr_in6*)sa)->sin6_addr);
}

int main(int argc, char *argv[])

{
int sockfd, numbytes;
char buf[MAXDATASIZE];
struct addrinfo hints, *servinfo, *p;
int rv;
char s[INET6_ADDRSTRLEN];
if (argc != 3) {
fprintf(stderr,"argument(s) missing\n");
exit(1);
}
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
if ((rv = getaddrinfo(argv[1], argv[2], &hints, &servinfo)) != 0)
{
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
return 1;
}
// loop through all the results and connect to the first we can
for(p = servinfo; p != NULL; p = p->ai_next)
{
if ((sockfd = socket(p->ai_family, p->ai_socktype,p->ai_protocol)) == -1)
{
perror("client: socket");
continue;
}
if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1)
{
close(sockfd);

perror("client: connect");
continue;
}
break;
}
if (p == NULL)
{
fprintf(stderr, "client: failed to connect\n");
return 2;
}
inet_ntop(p->ai_family, get_in_addr((struct sockaddr *)p->ai_addr),s, sizeof s);
printf("client: connecting to %s\n", s);
freeaddrinfo(servinfo); // all done with this structure
char Msg[100];
while(1)
{

printf("755/IT/12 ftp client : ");


printf("Enter message to be sent to server : ");
gets(Msg);
int ret;
if(strncmp(Msg,"c_",2) == 0)
{
if(strncmp(Msg+2,"ls",2) == 0)
system("ls");
else if(strncmp(Msg+2,"pwd",3) == 0)
system("pwd");
else if(strncmp(Msg+2,"cd",2) == 0)
{
system("pwd");
ret = chdir (Msg+5);

if(ret!=0)
perror("Error:");
system("pwd");
}
else
printf("An invalid FTP Command\n");
}
else if(strncmp(Msg,"s_",2) == 0)
{
char buf_s[1025];
if(strncmp(Msg+2,"ls",2) == 0)
{
send(sockfd,Msg+2,strlen(Msg+2),0);
int numbytes = recv(sockfd,buf_s,1023,0);
buf_s[numbytes] = '\0';
printf("%s",buf_s);
}
else if(strncmp(Msg+2,"pwd",3) == 0)
{
send(sockfd,Msg+2,strlen(Msg+2),0);
int numbytes = recv(sockfd,buf_s,1023,0);
buf_s[numbytes] = '\0';
printf("%s",buf_s);
}
else if(strncmp(Msg+2,"cd",2) == 0)
{
send(sockfd,Msg+2,strlen(Msg+2),0);
int numbytes = recv(sockfd,buf_s,1023,0);
buf_s[numbytes] = '\0';

printf("%s",buf_s);
}
else
printf("An invalid FTP Command\n");
}
else if(strncmp(Msg,"put",3) == 0)
{
FILE *fp = fopen(Msg+4,"r");
if(fp == NULL)
printf("%s:no such file on client\n",Msg+2);
else
{

char filebuf[1024];
int i = 0,ch;
while((ch = fgetc(fp)) != EOF)
filebuf[i++] = ch;
filebuf[i] = '\0';
send(sockfd,filebuf,strlen(filebuf),0);
printf("%s sent to the server\n",Msg+4);

}
fclose(fp);
}
else if(strncmp(Msg,"get",3) == 0)
{
send(sockfd,Msg,strlen(Msg),0);
char Buf[1000];
int num = recv(sockfd,Buf,sizeof(Buf),0);
Buf[num] = '\0';
if(strcmp(Buf,"File not found") == 0)
printf("File not found\n");

else
{
FILE *fp = fopen("newfile_client.txt","w");
int i;
for(i=0;Buf[i];i++)
fputc(Buf[i],fp);
fclose(fp);
}
}
else if(strncmp(Msg,"quit",4) == 0)
{
send(sockfd,Msg,sizeof(Msg),0);
close(sockfd);
return 0;
}
else
printf("An invalid FTP Command\n");
}
return 0;
}

FTP Server
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h> //for perror
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>

#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <signal.h>
#define PORT "3490" // the port users will be connecting to
#define BACKLOG 10

// how many pending connections queue will hold

void *get_in_addr(struct sockaddr *sa)


{
if (sa->sa_family == AF_INET) {
return &(((struct sockaddr_in*)sa)->sin_addr);
}
return &(((struct sockaddr_in6*)sa)->sin6_addr);
}
int main(void)
{
int sockfd, new_fd; // listen on sock_fd, new connection on new_fd
struct addrinfo hints, *servinfo, *p; //servinfo will point to hints
struct sockaddr_storage their_addr; // connector's address information
socklen_t sin_size;
int yes=1;
char buf[100];
char s[INET6_ADDRSTRLEN]; //#define in netinet/in.h Value is 46.INET_ADDRSTRLEN 16
int rv;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC; //IP can be either IPv4 or IPv6
hints.ai_socktype = SOCK_STREAM; // Stream socket
hints.ai_flags = AI_PASSIVE; // use my IP.attach IP of host to structure
if ((rv = getaddrinfo(NULL, PORT, &hints, &servinfo)) != 0) //servinfo stores info of all IP associate with host

{
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
return 1;
}
// loop through all the results and bind to the first we can
for(p = servinfo; p != NULL; p = p->ai_next)
{
if ((sockfd = socket(p->ai_family, p->ai_socktype,p->ai_protocol)) == -1) //Socket Connection is being
established
{
perror("server: socket");
continue;
}
if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) //binding to the host
{
close(sockfd);
perror("server: bind");
continue;
}
break;
}
if (p == NULL)
{
fprintf(stderr, "server: failed to bind\n");
return 2;
}
freeaddrinfo(servinfo); // all done with this structure

if (listen(sockfd, BACKLOG) == -1)

{
perror("listen");
exit(1);
}
printf("server: waiting for connections...\n");
int num;
while(1)
{ // main accept() loop
sin_size = sizeof their_addr;
new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size);
if (new_fd == -1)
{
perror("accept");
continue;
}
inet_ntop(their_addr.ss_family,get_in_addr((struct sockaddr *)&their_addr),s, sizeof s);
char Msg[100];
printf("server: got connection from %s\n", s);
while(1)
{
num = recv(new_fd,buf,sizeof(buf),0);
buf[num] = '\0';
if(strcmp(buf,"ls") == 0)
{
FILE *fp = popen("ls","r");
int size = 1000;
char ls_array[size];
fseek(fp,SEEK_SET,0);
int ch,i = 0;

while((ch = fgetc(fp)) != EOF)


ls_array[i++] =ch;
ls_array[i] = '\0';
send(new_fd,ls_array,strlen(ls_array),0);
}
else if(strcmp(buf,"pwd") == 0)
{
FILE *fp = popen("pwd","r");
int size = 1000;
char pwd_array[size];
fseek(fp,SEEK_SET,0);
int ch,i = 0;
while((ch = fgetc(fp)) != EOF)
pwd_array[i++] =ch;
pwd_array[i] = '\0';
send(new_fd,pwd_array,strlen(pwd_array),0);
}
else if(strncmp(buf,"cd",2) == 0)
{
int ret = chdir(buf+3);
if(ret == 0)
{
char suc[] ="Command executed succesfully on server.\n";
send(new_fd,suc,strlen(suc),0);
}
}
else if(strncmp(buf,"get",3) == 0)
{
char Buf[1000];

FILE *fp = fopen(buf+4,"r");


if(fp == NULL)
{
strcpy(Buf,"File not found");
send(new_fd,Buf,strlen(Buf),0);
}
else
{
int i=0,ch;
while((ch = fgetc(fp)) != EOF)
Buf[i++] = ch;
Buf[i] = '\0';
send(new_fd,Buf,strlen(Buf),0);
}
}
else if(strncmp(buf,"quit",4) == 0)
close(new_fd);
else //put
{
FILE *fp = fopen("newfile_server.txt","w");
int i;
for(i=0;buf[i];i++)
fputc(buf[i],fp);
fclose(fp);
}
}
close(new_fd); // parent doesn't need this
}

return 0;
}

FTP Server
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h> //for perror
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <signal.h>
#define PORT "3490" // the port users will be connecting to
#define BACKLOG 10

// how many pending connections queue will hold

// get sockaddr, IPv4 or IPv6:


void *get_in_addr(struct sockaddr *sa)
{
if (sa->sa_family == AF_INET) {
return &(((struct sockaddr_in*)sa)->sin_addr);
}
return &(((struct sockaddr_in6*)sa)->sin6_addr);
}
int main(void)
{
int sockfd, new_fd; // listen on sock_fd, new connection on new_fd

struct addrinfo hints, *servinfo, *p; //servinfo will point to hints


struct sockaddr_storage their_addr; // connector's address information
socklen_t sin_size;
char buf[100];
char s[INET6_ADDRSTRLEN]; //#define in netinet/in.h Value is 46.INET_ADDRSTRLEN 16
int rv;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC; //IP can be either IPv4 or IPv6
hints.ai_socktype = SOCK_STREAM; // Stream socket
hints.ai_flags = AI_PASSIVE; // use my IP.attach IP of host to structure
if ((rv = getaddrinfo(NULL, PORT, &hints, &servinfo)) != 0) //servinfo stores info of all IP associate with host
{
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
return 1;
}
for(p = servinfo; p != NULL; p = p->ai_next)
{
if ((sockfd = socket(p->ai_family, p->ai_socktype,p->ai_protocol)) == -1)
perror("server: socket");
continue;
}
if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) //binding to the host
{
close(sockfd);
perror("server: bind");
continue;
}
break;
}

if (p == NULL)
{
fprintf(stderr, "server: failed to bind\n");
return 2;
}
freeaddrinfo(servinfo); // all done with this structure
if (listen(sockfd, BACKLOG) == -1)
{
perror("listen");
exit(1);
}
printf("server: waiting for connections...\n");
int num;
while(1)
{ // main accept() loop
sin_size = sizeof their_addr;
new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size);
if (new_fd == -1)
{
perror("accept");
continue;
}
inet_ntop(their_addr.ss_family,get_in_addr((struct sockaddr *)&their_addr),s, sizeof s);
char Msg[100];
printf("server: got connection from %s\n", s);
while(1)
{

num = recv(new_fd,buf,sizeof(buf),0);

buf[num] = '\0';
if(strcmp(buf,"ls") == 0)
{
FILE *fp = popen("ls","r");
int size = 1000;
char ls_array[size];
fseek(fp,SEEK_SET,0);
int ch,i = 0;
while((ch = fgetc(fp)) != EOF)
ls_array[i++] =ch;
ls_array[i] = '\0';
send(new_fd,ls_array,strlen(ls_array),0);
}
else if(strcmp(buf,"pwd") == 0)
{
FILE *fp = popen("pwd","r");
int size = 1000;
char pwd_array[size];
fseek(fp,SEEK_SET,0);
int ch,i = 0;
while((ch = fgetc(fp)) != EOF)
pwd_array[i++] =ch;
pwd_array[i] = '\0';
send(new_fd,pwd_array,strlen(pwd_array),0);
}
else if(strncmp(buf,"cd",2) == 0)
{
int ret = chdir(buf+3);
if(ret == 0)

{
char suc[] ="Command executed succesfully on server.\n";
send(new_fd,suc,strlen(suc),0);
}
}
else if(strncmp(buf,"get",3) == 0)
{
char Buf[1000];
FILE *fp = fopen(buf+4,"r");
if(fp == NULL)
{
strcpy(Buf,"File not found");
send(new_fd,Buf,strlen(Buf),0);
}
else
{
int i=0,ch;
while((ch = fgetc(fp)) != EOF)
Buf[i++] = ch;
Buf[i] = '\0';
send(new_fd,Buf,strlen(Buf),0);
}
}
else if(strcmp(buf,"quit") == 0)
break;
else //put
{
FILE *fp = fopen("newfile_server.txt","w");
int i;

for(i=0;buf[i];i++)
fputc(buf[i],fp);
fclose(fp);
}
}
close(new_fd); // parent doesn't need this
}
return 0;
}

c) Write a server program that allows chatting among multiple clients.

Chat Client
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
#include<netdb.h>
#include<unistd.h>
#include<pthread.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<sys/types.h>
#include<sys/socket.h>
#define SERVERIP "127.0.0.1"
#define SERVERPORT 3490
#define BUFFSIZE 1024
#define ALIASLEN 32
#define OPTLEN 16
#define LINEBUFF 2048

struct PACKET
{
char option[OPTLEN];
char alias[ALIASLEN];
char buff[BUFFSIZE];
};
struct USER
{
int sockfd;
char alias[ALIASLEN];
};
struct THREADINFO
{
pthread_t thread_ID; //Handle for the new thread
int sockfd;
};
int isconnected,sockfd;
char option[LINEBUFF];
struct USER me;
int connect_with_server();
void logout(struct USER *me);
void login(struct USER *me);
void *receiver(void *param);
void sendtoall(struct USER *me, char *msg);
void sendtoalias(struct USER *me, char * target, char *msg);
void setalias(struct USER *me);
int main(int argc,char **argv)
{
int sockfd,aliaslen;

memset(&me,0,sizeof(struct USER));
while(gets(option))
{
if(!strncmp(option,"exit",4))
{
logout(&me);
break;
}
else if(!strncmp(option,"login",5))
{
char *ptr = strtok(option," ");
ptr = strtok(0," ");
memset(me.alias,0,sizeof(char)*ALIASLEN);
if(ptr)
{
aliaslen = strlen(ptr);
if(aliaslen > ALIASLEN)
ptr[ALIASLEN] = 0;
strcpy(me.alias,ptr);
}
else
strcpy(me.alias,"Anonymous");
login(&me);
}
else if(!strncmp(option,"sendto",6))
{
char *ptr = strtok(option," ");
char temp[ALIASLEN];
ptr = strtok(0," ");

memset(temp,0,sizeof(char)*ALIASLEN);
if(ptr)
{
aliaslen = strlen(ptr);
if(aliaslen > ALIASLEN)
ptr[ALIASLEN] = 0;
strcpy(temp,ptr);
while(*ptr)
ptr++;
ptr++;
while(*ptr <= ' ')
ptr++;
sendtoalias(&me,temp,ptr);
}
}
else if(!strncmp(option,"send",4))
sendtoall(&me,&option[5]);
else if(!strncmp(option,"logout",6))
logout(&me);
}
return 0;
}
void login(struct USER *me)
{
int recvd;
sockfd = connect_with_server();
if(sockfd >= 0)
{
isconnected = 1;

me->sockfd = sockfd;
if(strcmp(me->alias, "Anonymous"))
setalias(me);
printf("Logged in as %s\n",me->alias);
struct THREADINFO threadinfo;
pthread_create(&threadinfo.thread_ID,NULL,receiver,(void *)&threadinfo);
}
else
fprintf(stderr,"Connection rejected...\n");
}
int connect_with_server()
{
int newfd, err_ret;
struct sockaddr_in serv_addr;
struct hostent *to;
if((to = gethostbyname(SERVERIP))==NULL) {
err_ret = errno;
fprintf(stderr, "gethostbyname() error...\n");
return err_ret;
}
if((newfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
err_ret = errno;
fprintf(stderr, "socket() error...\n");
return err_ret;
}
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(SERVERPORT);
serv_addr.sin_addr = *((struct in_addr *)to->h_addr);
memset(&(serv_addr.sin_zero), 0, 8);

if(connect(newfd, (struct sockaddr *)&serv_addr, sizeof(struct sockaddr)) == -1) {


err_ret = errno;
fprintf(stderr, "connect() error...\n");
return err_ret;
}
else {
printf("Connected to server at %s:%d\n", SERVERIP, SERVERPORT);
return newfd;
}
}
void setalias(struct USER *me)
{
int sent;
struct PACKET packet;
if(!isconnected) {
fprintf(stderr, "You are not connected...\n");
return;
}
memset(&packet, 0, sizeof(struct PACKET));
strcpy(packet.option, "alias");
strcpy(packet.alias, me->alias);
sent = send(sockfd, (void *)&packet, sizeof(struct PACKET), 0);
}
void *receiver(void *param)
{
int recvd;
struct PACKET packet;

printf("Waiting here...\n");

while(isconnected)
{
recvd = recv(sockfd,(void *)&packet,sizeof(struct PACKET),0);
if(!recvd)
{
fprintf(stderr,"Connection lost from server...\n");
isconnected = 0;
close(sockfd);
break;
}
if(recvd > 0)
printf("[%s] : %s\n",packet.alias,packet.buff);
memset(&packet,0,sizeof(struct PACKET));
}
return NULL;
}
void logout(struct USER *me)
{
int sent;
struct PACKET packet;
if(!isconnected)
{
fprintf(stderr,"You are not connected..\n");
return ;
}
memset(&packet,0,sizeof(struct PACKET));
strcpy(packet.option,"exit");
strcpy(packet.alias,me->alias);
sent = send(sockfd,(void *)&packet,sizeof(struct PACKET),0);

isconnected = 0;
}
void sendtoall(struct USER *me,char *msg)
{
int sent;
struct PACKET packet;
if(!isconnected)
{
fprintf(stderr,"You are not connected...\n");
return;
}
msg[BUFFSIZE] = 0;
memset(&packet,0,sizeof(struct PACKET));
strcpy(packet.option,"send");
strcpy(packet.alias,me->alias);
strcpy(packet.buff,msg);
sent = send(sockfd,(void *)&packet,sizeof(struct PACKET),0);
}
void sendtoalias(struct USER *me,char *target,char *msg)
{
int sent,targetlen;
struct PACKET packet;
if(!target)
return;
if(!msg)
return;
if(!isconnected)
{
fprintf(stderr,"You are not connected...\n");

return ;
}
msg[BUFFSIZE] = 0;
targetlen = strlen(target);
memset(&packet,0,sizeof(struct PACKET));
strcpy(packet.option,"sendto");
strcpy(packet.alias,me->alias);
strcpy(packet.buff,target);
strcpy(&packet.buff[targetlen]," ");
strcpy(&packet.buff[targetlen+1],msg);
sent = send(sockfd,(void *)&packet,sizeof(struct PACKET),0);
}

Chat Server
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
#include<netdb.h>
#include<unistd.h>
#include<pthread.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<sys/types.h>
#include<sys/socket.h>
#define IP "127.0.0.1"
#define PORT 3490
#define BACKLOG 10
#define CLIENTS 10

#define BUFFSIZE 1024


#define ALIASLEN 32
#define OPTLEN 16
#define LINEBUFF 2048
struct PACKET
{
char option[OPTLEN];
char alias[ALIASLEN];
char buff[BUFFSIZE];
};
struct THREADINFO
{
pthread_t thread_ID;
int sockfd;
char alias[ALIASLEN];
};
struct LLNODE
{
struct THREADINFO threadinfo;
struct LLNODE *next;
};
struct LLIST
{
struct LLNODE *head,*tail;
int size;
};
int compare(struct THREADINFO *A,struct THREADINFO *B)
{
return A->sockfd - B->sockfd;

}
void list_init(struct LLIST *ll)
{
ll->head = ll->tail = NULL;
ll->size = 0;
}
int list_insert(struct LLIST *ll,struct THREADINFO *thr_info)
{
if(ll->size == CLIENTS) //Server limit of handling no. of clients is 10
return -1;
if(!ll->head)
{
ll->head = (struct LLNODE *)malloc(sizeof(struct LLNODE));
ll->head->threadinfo = *thr_info;
ll->head->next = NULL;
ll->tail = ll->head;
}
else
{
ll->tail->next = (struct LLNODE *)malloc(sizeof(struct LLNODE));
ll->tail->next->threadinfo = *thr_info;
ll->tail->next->next = NULL;
ll->tail = ll->tail->next;
}
ll->size++;
return 0;
}
int list_delete(struct LLIST *ll,struct THREADINFO *thr_info)
{

struct LLNODE *curr,*temp;


if(!ll->head)
return -1;
if(compare(thr_info,&ll->head->threadinfo) == 0)
{
temp = ll->head;
ll->head = ll->head->next;
if(!ll->head)
ll->tail = ll->head;
free(temp);
ll->size--;
return 0;
}
for(curr = ll->head;curr->next!=NULL ;curr = curr->next)
{
if(compare(thr_info,&curr->next->threadinfo) == 0)
{
temp = curr->next;
if(temp == ll->tail)
ll->tail = curr;
curr->next = curr->next->next;
free(temp);
ll->size--;
return 0;
}
}
return -1;
}
void list_dump(struct LLIST *ll)

{
struct LLNODE *curr;
struct THREADINFO *thr_info;
printf("Connection Count : %d\n",ll->size);
int i = 1;
for(curr = ll->head;curr;curr = curr->next)
{
thr_info = &curr->threadinfo;
printf("%d) %s\n",i++,thr_info->alias);
}
}
int sockfd,newfd;
struct THREADINFO thread_info[CLIENTS];
struct LLIST client_list;
pthread_mutex_t clientlist_mutex;
void *client_handler(void *fd);
void *io_handler(void *param);
int main(int argc,char **argv)
{
int err_ret,sin_size;
struct sockaddr_in serv_addr,client_addr;
pthread_t interrupt;
list_init(&client_list);
pthread_mutex_init(&clientlist_mutex,NULL);
if((sockfd = socket(AF_INET,SOCK_STREAM,0)) == -1)
{
err_ret = errno;
fprintf(stderr,"socket() failed...\n");
return err_ret;

}
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
serv_addr.sin_addr.s_addr = inet_addr(IP);
memset(&(serv_addr.sin_zero), 0, 8);
if(bind(sockfd, (struct sockaddr *)&serv_addr, sizeof(struct sockaddr)) == -1) {
err_ret = errno;
fprintf(stderr, "bind() failed...\n");
return err_ret;
}
if(listen(sockfd, BACKLOG) == -1) {
err_ret = errno;
fprintf(stderr, "listen() failed...\n");
return err_ret;
}
if(pthread_create(&interrupt, NULL, io_handler, NULL) != 0) {
err_ret = errno;
fprintf(stderr, "pthread_create() failed...\n");
return err_ret;
}
printf("server: waiting for connections...\n");
while(1)
{
sin_size = sizeof(struct sockaddr_in);
if((newfd = accept(sockfd,(struct sockaddr *)&client_addr,(socklen_t *)&sin_size)) == -1)
{
err_ret = errno;
fprintf(stderr,"accept() failed...\n");
return err_ret;

}
else
{
if(client_list.size == CLIENTS)
{
fprintf(stderr,"Connection full, request rejected...\n");
continue;
}
printf("Connection requested received...\n");
struct THREADINFO threadinfo;
threadinfo.sockfd = newfd;
strcpy(threadinfo.alias,"Anonymous");
pthread_mutex_lock(&clientlist_mutex);
list_insert(&client_list,&threadinfo);
pthread_mutex_unlock(&clientlist_mutex);
pthread_create(&threadinfo.thread_ID,NULL,client_handler,(void *)&threadinfo);
}
}
return 0;
}
void *io_handler(void *param)
{
char option[OPTLEN];
while(scanf("%s",option) == 1)
{
if(!strcmp(option,"exit"))
{
printf("Termination server...\n");
pthread_mutex_destroy(&clientlist_mutex);

close(sockfd);
exit(0);
}
else if(!strcmp(option,"list"))
{
pthread_mutex_lock(&clientlist_mutex);
list_dump(&client_list);
pthread_mutex_unlock(&clientlist_mutex);
}
else
fprintf(stderr,"Unknown command : %s...\n",option);
}
return NULL;
}
void *client_handler(void *fd)
{
struct THREADINFO threadinfo = *(struct THREADINFO *)fd;
struct PACKET packet;
struct LLNODE *curr;
int bytes,sent;
while(1)
{
bytes = recv(threadinfo.sockfd,(void *)&packet,sizeof(struct PACKET),0);
if(!bytes)
{
fprintf(stderr,"Connection lost from %s...\n",threadinfo.alias);
pthread_mutex_lock(&clientlist_mutex);
list_delete(&client_list,&threadinfo);
pthread_mutex_unlock(&clientlist_mutex);

break;
}
printf("Request : %s %s %s\n",packet.option,packet.alias,packet.buff);
if(!strcmp(packet.option, "alias"))
{
printf("Alias set to %s\n", packet.alias);
pthread_mutex_lock(&clientlist_mutex);
for(curr = client_list.head; curr != NULL; curr = curr->next)
{
if(compare(&curr->threadinfo, &threadinfo) == 0)
{
strcpy(curr->threadinfo.alias, packet.alias);
strcpy(threadinfo.alias, packet.alias);
break;
}
}
pthread_mutex_unlock(&clientlist_mutex);
}
else if(!strcmp(packet.option,"sendto"))
{
int i;
char target[ALIASLEN];
for(i=0;packet.buff[i] != ' ';i++);
packet.buff[i++] = 0;
strcpy(target,packet.buff);
pthread_mutex_lock(&clientlist_mutex);
for(curr = client_list.head;curr;curr = curr->next)
{
if(strcmp(target,curr->threadinfo.alias) == 0)

{
struct PACKET spacket;
memset(&spacket,0,sizeof(struct PACKET));
if(!compare(&curr->threadinfo,&threadinfo))
continue;
strcpy(spacket.option,"msg");
strcpy(spacket.alias,packet.alias);
strcpy(spacket.buff,&packet.buff[i]);
sent = send(curr->threadinfo.sockfd,(void *)&spacket,sizeof(struct PACKET),0);
}
}
pthread_mutex_unlock(&clientlist_mutex);
}
else if(!strcmp(packet.option,"send"))
{
pthread_mutex_lock(&clientlist_mutex);
for(curr = client_list.head;curr;curr = curr->next)
{
struct PACKET spacket;
memset(&spacket,0,sizeof(struct PACKET));
if(!compare(&curr->threadinfo,&threadinfo))
continue;
strcpy(spacket.option,"msg");
strcpy(spacket.alias,packet.alias);
strcpy(spacket.buff,packet.buff);
sent = send(curr->threadinfo.sockfd,(void *)&spacket,sizeof(struct PACKET),0);
}
pthread_mutex_unlock(&clientlist_mutex);
}

else if(!strcmp(packet.option,"exit"))
{
printf("[%d] %s has disconnected...]\n",threadinfo.sockfd,threadinfo.alias);
pthread_mutex_lock(&clientlist_mutex);
list_delete(&client_list,&threadinfo);
pthread_mutex_unlock(&clientlist_mutex);
break;
}
else
fprintf(stderr,"Garbage data from [%d] %s...\n",threadinfo.sockfd,threadinfo.alias);
}
close(threadinfo.sockfd);
return NULL;
}

Q3)
a) Write a C program to display the currently configured Network Parameters (IP Address, Netmask,
Default Gateway, DNS Servers, Hardware Address, Broadcast Address etc.) for the network interface
currently active on your computer.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>

int main(void)
{
char str1[500],prev[500],ch;
int flag = 0;
system("ifconfig eth0 > input.txt");
FILE *fp1 = fopen("input.txt","r");
FILE *fp2 = fopen("output.txt","w");

while(!feof(fp1))
{
fscanf(fp1,"%s",str1);
if(strcmp(str1,"eth0") == 0)
fprintf(fp2,"Network Parameters\n");
else if(strcmp(str1,"HWaddr") == 0)
{
fscanf(fp1,"%s",str1);
fprintf(fp2,"Hardware Address - %s\n",str1);
}
else if(strstr(str1,"addr") != 0 && strcmp(prev,"inet") == 0 && flag == 0)
{
char *ptr = str1;
while(*ptr != ':')
ptr++;
fprintf(fp2,"IP Address - %s\n",ptr+1);
}
else if(strstr(str1,"Bcast") != 0)
{
char *ptr = str1;
while(*ptr != ':')
ptr++;
fprintf(fp2,"Broadcast Address - %s\n",ptr+1);
}
else if(strstr(str1,"Mask") != 0 && !flag)
{
char *ptr = str1;
while(*ptr != ':')
ptr++;

fprintf(fp2,"Netmask - %s\n",ptr+1);
}
strcpy(prev,str1);
}
fclose(fp1);
system("route > input.txt");
fp1 = fopen("input.txt","r");
while(!feof(fp1))
{
fscanf(fp1,"%s",str1);
if(strcmp(str1,"default") == 0)
{
fscanf(fp1,"%s",str1);
fprintf(fp2,"Default Gateway - %s\n",str1);
}
strcpy(prev,str1);
}
printf("\n");
fclose(fp1);
system("cat /etc/resolv.conf > input.txt");
fp1 = fopen("input.txt","r");
while(!feof(fp1))
{
fscanf(fp1,"%s",str1);
if(strcmp(str1,"nameserver") == 0)
{
fscanf(fp1,"%s",str1);
fprintf(fp2,"DNS Server - %s\n",str1);
}

strcpy(prev,str1);
}
fclose(fp1);
fclose(fp2);
fp2 = fopen("output.txt","r");
while(!feof(fp2))
{
fscanf(fp2,"%c",&ch);
printf("%c",ch);
}
fclose(fp2);
system("rm input.txt output.txt");
return 0;
}

b) Open the pcap dump file (a binary file) using C program. Read the PCAP file structure. Retrieve the
header information from the binary file and show it on the display. Write a C program to compute
checksum.
#include<stdio.h>
#include<stdlib.h>
struct ether
{
unsigned char ether_dest[6];
unsigned char ether_src[6];
}e;
struct readip
{
char verhl; //version and header length
char ver,hl;
unsigned int tlen;

int protocol;
unsigned char checksum[2];
unsigned char src[4];
unsigned char dest[4];
}ip;
struct tcp
{
unsigned short int srcport;
unsigned short int destport;
unsigned char seq[4],ack[4];
char size;
unsigned short int window;
}tcp;
void conversion(char *verhl,char *ver,char *hl)
{
*ver = (*verhl) & (0xf0);
*ver = (*ver) >> 4;
*hl = (*verhl) & (0x0f);
}
int checksum(char *addr,int count)
{
long sum = 0;
unsigned short checksum,conv;
while(count > 1)
{
conv = ntohs(*(unsigned short *)addr);
sum += conv;
addr += 2;
count-= 2;

}
if(count > 0)
{
conv = ntohs(*(char *)addr);
sum += conv;
}
while(sum >> 16)
sum = (sum & 0xffff) + (sum >> 16);
return ~checksum;
}
int main(void)
{
FILE *fp = fopen("pa.pcap","rb");
char *data = (char *)malloc(1000*sizeof(char));
fseek(fp,0,SEEK_SET);
int beg = ftell(fp);
fseek(fp,0,SEEK_END);
int end = ftell(fp);
fseek(fp,0,SEEK_SET);
fread(data,1,end-beg,fp);
int i = 40,j;
data = data + 40;
while(i < 46)
{
e.ether_dest[i-40] = *(data)++;
i++;
}
printf("\nEthernet Destination : ");
for(j=0;j<6;j++)

if(j != 0)
printf(":%.2x",e.ether_dest[j]);
else
printf("%.2x",e.ether_dest[j]);
printf("\n");
while(i < 52)
{
e.ether_src[i-46] = *(data)++;
i++;
}
printf("Ethernet Source : ");
for(j=0;j<6;j++)
if(j != 0)
printf(":%.2x",e.ether_src[j]);
else
printf("%.2x",e.ether_src[j]);
printf("\n");
printf("Type : IP (0x%.2x%.2x)",*data,*(data+1));
printf("\n");
printf("\nIP Header : ");
char *ipstart = data + 2;
ip.verhl = *ipstart;
conversion(&ip.verhl,&ip.ver,&ip.hl);
printf("\nIP Version : %d \nHeader length : %d bytes\n",(int)ip.ver,(int)ip.hl*4);
ip.tlen = *(ipstart+2);
ip.tlen = (ip.tlen << 8) | (*(ipstart+3));
printf("IP Total length : %d\n",ip.tlen);
ip.protocol = (int) *(ipstart + 9);
switch(ip.protocol)

{
case 1 : printf("Protocol : ICMP(%d)\n",ip.protocol); break;
case 2 : printf("Protocol : IGMP(%d)\n",ip.protocol); break;
case 6 : printf("Protocol : TCP(%d)\n",ip.protocol); break;
case 17 : printf("Protocol : UDP(%d)\n",ip.protocol); break;
default : printf("Protocol : %d\n",ip.protocol);
}
for(j=0;j<4;j++)
{
ip.src[j] = *(ipstart + 12 + j);
ip.dest[j] = *(ipstart + 16 + j);
}
printf("IP source : ");
for(j=0;j<4;j++)
if(j != 3)
printf("%d.",(unsigned int)ip.src[j]);
else
printf("%d",(unsigned int)ip.src[j]);
printf("\nIP destination : ");
for(j=0;j<4;j++)
if(j != 3)
printf("%d.",(unsigned int)ip.dest[j]);
else
printf("%d",(unsigned int)ip.dest[j]);
printf("\n");
ip.checksum[0] = (*(ipstart + 10));
ip.checksum[1] = (*(ipstart + 11));

printf("Header checksum : 0x%x%x\n",ip.checksum[0],ip.checksum[1]);

if(checksum(ipstart,(int)ip.hl*4) == 0)
printf("The IP header does not have any error\n");
else
printf("The IP header has some error\n");
char *tcpstart = ipstart + ((int)ip.hl)*4;
tcp.srcport = (*(tcpstart) << 8) | (*(tcpstart+1) & 0x00ff);
tcp.destport = (*(tcpstart + 2) << 8) | (*(tcpstart+3) & 0x00ff);
if(ip.protocol == 6)
printf("\nTCP Header : \n");
else if(ip.protocol == 17)
printf("\nUDP Header : \n");
printf("Source port : %d\n",tcp.srcport);
printf("Destination port : %d\n",tcp.destport);
if(ip.protocol == 6)
{
for(i=0;i<4;i++)
{
tcp.seq[i] = *(tcpstart+4+i);
tcp.ack[i] = *(tcpstart+8+i);
}
printf("Sequence number : ");
for(i=0;i<4;i++)
printf("%.2x ",tcp.seq[i]);
printf("\n");
printf("Acknowledgement number : ");
for(i=0;i<4;i++)
printf("%.2x ",tcp.ack[i]);
printf("\n");
}

tcp.size = *(tcpstart + 12);


tcp.size = (tcp.size >> 4) & (0x0f);
printf("Header Length : %d bytes\n",tcp.size*4);
if(ip.protocol == 6)
{
tcp.window = (*(tcpstart+14)<<8) | (*(tcpstart+15) & 0x00ff);
printf("Window Size = %d",tcp.window);

}
printf("\n\n");
return 0;
}