CN Assignment 20105034 Saksham Garg

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 19

CN Assignment – 3

By: Saksham Garg


SID: 20105034

Ques1: Write and explain the basic commands to edit, compile and execute ‘C’
programs in Linux Environment?
Ans 1:
To Edit: Use a text editor to create or edit your C program. For example, using
Vim: This will open the Vim editor with a new or existing file named saksham.c.
Command: vim saksham.c

To Compile: The GNU Compiler Collection (GCC) is a commonly used compiler for
C programs on Linux.
In the terminal, we use the following command to compile your C program:
Command: gcc -o output_file saksham.c

To Execute: Once the compilation is successful, we can run the compiled program
using the following command:
Command: . /output_file
The program will now execute, and we'll see the output in the terminal.

Ques 2: Write basic code with brief explanation of the basics of sockets
programming using ‘C’
Programming Language in Linux based environment for follwing
a. Creating and destroying sockets – socket() and close() functions
b. Specifying addresses – sockaddr and sockaddr_in structures
c. Understanding the syntax, purpose and use of various functions used in sockets
programing in ‘C’ programming language – connect(), send(), recv(), bind(),
listen(), accept(), sendto(), recvfrom() etc. functions
Ans 2:
a) Code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>

int main() {
int server_socket = socket(AF_INET, SOCK_STREAM, 0);
if (server_socket == -1) {
perror("Error creating socket");
exit(EXIT_FAILURE);
}

printf("Socket created successfully\n");


if (close(server_socket) == -1) {
perror("Error closing socket");
exit(EXIT_FAILURE);
}
printf("Socket closed successfully\n");
return 0;
}
Explanation:
 socket() is used to create a new socket.
 It takes three arguments:
o AF_INET: Address family (IPv4).
o SOCK_STREAM: Type of socket (in this case, a stream socket, which is TCP).
o 0: Protocol (0 specifies the default protocol for the given socket type).
 After creating the socket, it's important to check if the creation was successful.
If not, an error message is printed, and the program exits.
 At this point, you can perform various operations using the created socket.
 close() is used to close the socket when it is no longer needed.
 It takes the socket descriptor as an argument.
 Again, error checking is done to ensure the socket is closed properly.
 If all operations are successful, the program prints messages indicating that the
socket was created and closed successfully.

b)
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>

#define PORT 8080


#define MAX_CONNECTIONS 5

int main() {
int server_fd, new_socket;
struct sockaddr_in server_addr, client_addr;
socklen_t addr_len = sizeof(client_addr);

if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1)


{ perror("Socket creation failed");
exit(EXIT_FAILURE);
}

memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = INADDR_ANY;
server_addr.sin_port = htons(PORT);

if (bind(server_fd, (struct sockaddr*)&server_addr, sizeof(server_addr)) == -1)


{ perror("Bind failed");
exit(EXIT_FAILURE);
}

if (listen(server_fd, MAX_CONNECTIONS) == -1)


{ perror("Listen failed");
exit(EXIT_FAILURE);
}

printf("Server listening on port %d...\n", PORT);

if ((new_socket = accept(server_fd, (struct sockaddr*)&client_addr, &addr_len)) == -1)


{ perror("Accept failed");
exit(EXIT_FAILURE);
}

printf("Connection accepted from %s:%d\n", inet_ntoa(client_addr.sin_addr),


ntohs(client_addr.sin_port));

close(new_socket);
close(server_fd);

return 0;
}

Explanation:
 socket(AF_INET, SOCK_STREAM, 0): Creates a new socket using IPv4 and TCP.
 bind(server_fd, (struct sockaddr*)&server_addr, sizeof(server_addr)):
Associates the socket with the specified address and port.
 listen(server_fd, MAX_CONNECTIONS): Listens for incoming connections with
a maximum queue size.
 accept(server_fd, (struct sockaddr*)&client_addr, &addr_len): Accepts an
incoming connection and returns a new socket for data exchange.
 The struct sockaddr_in structure is used to represent the server and client
addresses.

c)
Code:
Server.c(server side)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>

#define PORT 8080


#define BUFFER_SIZE 1024

int main() {
int server_fd, new_socket;
struct sockaddr_in server_addr, client_addr;
int opt = 1;
int addrlen = sizeof(server_addr);
char buffer[BUFFER_SIZE] = {0};

if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0)


{ perror("Socket creation failed");
exit(EXIT_FAILURE);
}

if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT,


&opt, sizeof(opt))) {
perror("setsockopt failed");
exit(EXIT_FAILURE);
}
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = INADDR_ANY;
server_addr.sin_port = htons(PORT);

if (bind(server_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0)


{ perror("Bind failed");
exit(EXIT_FAILURE);
}

if (listen(server_fd, 3) < 0)
{ perror("Listen failed");
exit(EXIT_FAILURE);
}

if ((new_socket = accept(server_fd, (struct sockaddr *)&client_addr,


(socklen_t*)&addrlen)) < 0) {
perror("Accept failed");
exit(EXIT_FAILURE);
}

if (recv(new_socket, buffer, BUFFER_SIZE, 0) < 0)


{ perror("Receive failed");
exit(EXIT_FAILURE);
}
printf("Received message from client: %s\n", buffer);

char *response = "Hello from server!";


send(new_socket, response, strlen(response), 0);
printf("Response sent to client\n");

close(new_socket);
close(server_fd);
return 0;
}
Client.c(client side)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>

#define PORT 8080


#define BUFFER_SIZE 1024

int main() {
int sock = 0;
struct sockaddr_in server_addr;
char buffer[BUFFER_SIZE] = {0};

if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)


{ perror("Socket creation failed");
exit(EXIT_FAILURE);
}

server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(PORT);

if (inet_pton(AF_INET, "127.0.0.1", &server_addr.sin_addr) <= 0)


{ perror("Invalid address/ Address not supported");
exit(EXIT_FAILURE);
}

if (connect(sock, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0)


{ perror("Connection Failed");
exit(EXIT_FAILURE);
}

char *message = "Hello from client!";


send(sock, message, strlen(message), 0);
printf("Message sent to server\n");

if (recv(sock, buffer, BUFFER_SIZE, 0) < 0) {


perror("Receive failed");
exit(EXIT_FAILURE);
}
printf("Server response: %s\n", buffer);

close(sock);
return 0;
}
Explanation:
connect(): This function is used to connect a socket to a server. It takes the socket file descriptor, the
server address, and the length of the server address as arguments.

send(): This function is used to send data over the socket. It takes the socket file descriptor, the message
to be sent, the length of the message, and flags as arguments.

recv(): This function is used to receive data from the socket. It takes the socket file descriptor, the buffer
to store the received data, the maximum length of the data to be received, and flags as arguments.

bind(): This function is used to bind a socket to a particular address and port. It takes the socket file
descriptor, the address to bind to, and the length of the address as arguments.

listen(): This function is used to put the socket in listening mode. It takes the socket file descriptor and
the maximum number of pending connections as arguments.

accept(): This function is used to accept a connection request from a client. It takes the socket file
descriptor, the address of the client, and the length of the address as arguments.

sendto(): This function is used to send data to a specific address. It takes the socket file descriptor, the
message to be sent, the length of the message, flags, the address to send to, and the length of the
address as arguments.

recvfrom(): This function is used to receive data from a specific address. It takes the socket file
descriptor, the buffer to store the received data, the maximum length of the data to be received, flags,
the address from which to receive, and the length of the address as arguments.

Ques3: TCP/IP based Echo Client program using ‘C’ Programming Language in
Linux based environment
Ans3:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>

#define PORT 8080


#define MAX_BUFFER_SIZE 1024

int main() {
int client_socket;
struct sockaddr_in server_addr;
char buffer[MAX_BUFFER_SIZE];

if ((client_socket = socket(AF_INET, SOCK_STREAM, 0)) == -1)


{ perror("Socket creation failed");
exit(EXIT_FAILURE);
}

server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(PORT);

if (inet_pton(AF_INET, "127.0.0.1", &server_addr.sin_addr) <= 0)


{ perror("Invalid address/ Address not supported");
exit(EXIT_FAILURE);
}

if (connect(client_socket, (struct sockaddr *)&server_addr, sizeof(server_addr))


== -1) {
perror("Connection failed");
exit(EXIT_FAILURE);
}

printf("Connected to server on port %d\n", PORT);

while (1) {
printf("Enter message to send (type 'exit' to quit): ");
fgets(buffer, MAX_BUFFER_SIZE, stdin);

send(client_socket, buffer, strlen(buffer), 0);

if (strncmp(buffer, "exit", 4) == 0)
break;

recv(client_socket, buffer, MAX_BUFFER_SIZE, 0);


printf("Received from server: %s", buffer);
}

close(client_socket);
return 0;
}

Ques4: TCP/IP based Echo server program using ‘C’ Programming Language in
Linux based environment
Ans4:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>

#define PORT 8080


#define MAX_BUFFER_SIZE 1024

int main() {
int server_socket, client_socket;
struct sockaddr_in server_addr, client_addr;
char buffer[MAX_BUFFER_SIZE];

if ((server_socket = socket(AF_INET, SOCK_STREAM, 0)) == -1)


{ perror("Socket creation failed");
exit(EXIT_FAILURE);
}
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = INADDR_ANY;
server_addr.sin_port = htons(PORT);

if (bind(server_socket, (struct sockaddr *)&server_addr, sizeof(server_addr)) ==


-1) {
perror("Bind failed");
exit(EXIT_FAILURE);
}

if (listen(server_socket, 3) == -1)
{ perror("Listen failed");
exit(EXIT_FAILURE);
}

printf("Server listening on port %d...\n", PORT);

socklen_t addr_len = sizeof(client_addr);

if ((client_socket = accept(server_socket, (struct sockaddr *)&client_addr,


&addr_len)) == -1) {
perror("Accept failed");
exit(EXIT_FAILURE);
}
printf("Connection accepted from %s:%d\n", inet_ntoa(client_addr.sin_addr),
ntohs(client_addr.sin_port));

while (1) {
ssize_t received_bytes = recv(client_socket, buffer, MAX_BUFFER_SIZE, 0);
if (received_bytes <= 0) {
printf("Client disconnected\n");
break;
}

send(client_socket, buffer, received_bytes, 0);


buffer[received_bytes] = '\0';

printf("Received from client: %s", buffer);


}

close(client_socket);
close(server_socket);

return 0;
}

Ques 5: UDP/IP based Echo Client Program using ‘C’ Programming Language in
Linux based environment
Ans 5:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>

#define SERVER_IP "127.0.0.1"


#define SERVER_PORT 8080
#define BUFFER_SIZE 1024

int main() {
int clientSocket;
struct sockaddr_in serverAddr;
char buffer[BUFFER_SIZE];

if ((clientSocket = socket(AF_INET, SOCK_DGRAM, 0)) == -1)


{ perror("Error creating socket");
exit(EXIT_FAILURE);
}

memset(&serverAddr, 0, sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(SERVER_PORT);
inet_pton(AF_INET, SERVER_IP, &serverAddr.sin_addr);

printf("Enter message to send (type 'exit' to quit):\n");

while (1) {
fgets(buffer, BUFFER_SIZE, stdin);
sendto(clientSocket, buffer, strlen(buffer), 0, (struct sockaddr*)&serverAddr,
sizeof(serverAddr));

if (strncmp(buffer, "exit", 4) == 0)
break;

ssize_t recvBytes = recvfrom(clientSocket, buffer, BUFFER_SIZE, 0, NULL,


NULL);

if (recvBytes == -1)
{ perror("Error receiving
data"); exit(EXIT_FAILURE);
}

buffer[recvBytes] = '\0';
printf("Server response: %s", buffer);
}

close(clientSocket);
return 0;
}

Ques6: UDP/IP based Echo Server Program using ‘C’ Programming Language in
Linux based environment
Ans 6:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>

#define SERVER_PORT 8080


#define BUFFER_SIZE 1024

int main() {
int serverSocket;
struct sockaddr_in serverAddr, clientAddr;
socklen_t clientAddrLen = sizeof(clientAddr);
char buffer[BUFFER_SIZE];

if ((serverSocket = socket(AF_INET, SOCK_DGRAM, 0)) == -1)


{ perror("Error creating socket");
exit(EXIT_FAILURE);
}

memset(&serverAddr, 0, sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_addr.s_addr = INADDR_ANY;
serverAddr.sin_port = htons(SERVER_PORT);

if (bind(serverSocket, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) == -1)


{
perror("Error binding socket");
exit(EXIT_FAILURE);
}

printf("UDP Echo Server is listening on port %d...\n", SERVER_PORT);

while (1) {
ssize_t recvBytes = recvfrom(serverSocket, buffer, BUFFER_SIZE, 0, (struct
sockaddr*)&clientAddr, &clientAddrLen);

if (recvBytes == -1)
{ perror("Error receiving
data"); exit(EXIT_FAILURE);
}

buffer[recvBytes] = '\0';
printf("Received from %s:%d: %s", inet_ntoa(clientAddr.sin_addr),
ntohs(clientAddr.sin_port), buffer);

sendto(serverSocket, buffer, recvBytes, 0, (struct sockaddr*)&clientAddr,


sizeof(clientAddr));
}

close(serverSocket);

return 0;
}

You might also like