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

COMPUTER NETWORKS

Reg.no : 22BRS1303
Name : Nisha Dipak gote
Course Code : BCSE308P
Course Title : COMPUTER NETWORKS
LAB Slot : L5+L6
Faculty Name : DR.A.SWAMINATHAN

QUESTION: Using the given components and devices, such as routers, switches and cat6 cables,
create a of any topology. Configure the router and configure the IP for all n nodes connected in the
network using dynamic DHCP. Write a UDP Client Server program to perform a
multiuser chat program.

SERVER CODE:
#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#include <arpa/inet.h>

#define PORT 12345

#define BUFFER_SIZE 1024

int main() {

int sockfd;

struct sockaddr_in server_addr, client_addr;

socklen_t client_len;

char buffer[BUFFER_SIZE];

// Create UDP socket

sockfd = socket(AF_INET, SOCK_DGRAM, 0);

if (sockfd < 0) {

perror("Socket creation failed")

exit(EXIT_FAILURE);
}

// Initialize server address structure

memset(&server_addr, 0, sizeof(server_addr));

server_addr.sin_family = AF_INET;

server_addr.sin_addr.s_addr = htonl(INADDR_ANY);

server_addr.sin_port = htons(PORT);

// Bind the socket to the server address

if (bind(sockfd, (const struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {

perror("Bind failed");

exit(EXIT_FAILURE);

printf("Server started. Waiting for messages...\n");

while (1) {

// Receive message from client

memset(buffer, 0, BUFFER_SIZE);

int recv_len = recvfrom(sockfd, buffer, BUFFER_SIZE, 0, (struct sockaddr *)&client_addr, &client_len);

if (recv_len < 0) {

perror("Error in receiving message");

exit(EXIT_FAILURE);

printf("Received message from %s:%d: %s\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port), buffer);

close(sockfd);

return 0;

CLIENT CODE:
#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#include <arpa/inet.h>

#define PORT 12345

#define BUFFER_SIZE 1024


int main() {

int sockfd;

struct sockaddr_in server_addr;

char buffer[BUFFER_SIZE];

// Create UDP socket

sockfd = socket(AF_INET, SOCK_DGRAM, 0);

if (sockfd < 0) {

perror("Socket creation failed");

exit(EXIT_FAILURE);

// Initialize server address structure

memset(&server_addr, 0, sizeof(server_addr));

server_addr.sin_family = AF_INET;

server_addr.sin_addr.s_addr = inet_addr("192.168.1.1"); // Replace with the server's IP address

server_addr.sin_port = htons(PORT);

while (1) {

// Input message from user

printf("Enter your message: ");

fgets(buffer, BUFFER_SIZE, stdin);

// Send message to server

if (sendto(sockfd, buffer, strlen(buffer), 0, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {

perror("Error in sending message");

exit(EXIT_FAILURE);

close(sockfd);

return 0;

}
OUTPUT:
:

You might also like