ASSIGNMENT 3 Network Programming
ASSIGNMENT 3 Network Programming
Members
You are supposed write two separate TCP socket programs that implements both Client/Server
parts of a communication such that Client will send two integers and Server will reply with the
sum of those integers. In your programs you should clearly indicate the header files that are used
a) Write the client_add.c client program that take the two integers as an argument input to the
program or in run-time from the user. After receiving the reply of the Server, Client will
show the user final result. You can use sprintf() function to convert an integer to a string, and
b) Write the server_add.c server program that replies with the sum of numbers received from
the client program. The server process should work in connection-oriented and concurrentserver
mode.
c) At the terminal, indicate how the two programs are compiled, build and executed
d) At the terminal, use netstat to indicate how TCP connection, establishment and termination
Answers:
Client_add.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
int sock;
char buffer[1024];
num1 = atoi(argv[1]);
num2 = atoi(argv[2]);
} else {
exit(1);
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(SERVER_PORT);
server_addr.sin_addr.s_addr = inet_addr(SERVER_IP);
perror("Connection failed");
exit(1);
sum = atoi(buffer);
close(sock);
return 0;
The code is then saved on emacs, we have used emacs as our editor
The following command is run to open emacs:
emacs client_add.c
2. Server_add.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
close(client_sock);
exit(0);
}
int main() {
int server_sock, client_sock;
struct sockaddr_in server_addr, client_addr;
socklen_t addr_size;
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(SERVER_PORT);
server_addr.sin_addr.s_addr = INADDR_ANY;
if (listen(server_sock, 5) == -1) {
perror("Listen failed");
exit(1);
}
while (1) {
addr_size = sizeof(client_addr);
client_sock = accept(server_sock, (struct sockaddr *)&client_addr, &addr_size);
if (client_sock == -1) {
perror("Accept failed");
continue;
}
if (fork() == 0) {
close(server_sock);
handle_client(client_sock);
}
close(client_sock);
}
return 0;
}
Here are the screenshots when saving the code to emac editor
Now we use gcc to compile the programs, and here are the commands to run:
Now we run the client on a new terminal and we enter the two numbers using the following
command:
./client 10 12
Now we check the TCP Connections using Netstat and we are going to run the following
command:
netstat -tanp | grep :8080
This shows: