Computer Network Lab File

Download as pdf or txt
Download as pdf or txt
You are on page 1of 18

Index

S.no. Topic

1. Write a code simulating ARP/RARP protocol in C

Write a code simulating PING and TRACEROUTE command in C


2.

Write a program to implement RPC (remote procedure call) in c


3.

4. Write a c program to find IP address, subnet mask and default gateway

5. Write a c program why socket programming using UDP and TCP (e.g. simple DNS, data
and time client/server, echo client/server, iterative and concurrent server)
1. Write a code simulating ARP/RARP protocol in c.

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#define MAX_DEVICES 10

#define MAX_IP_LENGTH 16

#define MAX_MAC_LENGTH 18

typedef struct {

char ip[MAX_IP_LENGTH];

char mac[MAX_MAC_LENGTH];

} Device;

Device devices[MAX_DEVICES];

int numDevices = 0;

void sendARPRequest(const char* ip) {

printf("Sending ARP request for IP: %s\n", ip);

// Search for MAC address in the devices array

int i;

for (i = 0; i < numDevices; i++) {

if (strcmp(devices[i].ip, ip) == 0) {

printf("ARP reply received! MAC address: %s\n", devices[i].mac);

return;

printf("ARP request failed. IP address not found.\n");


}

void sendRARPRequest(const char* mac) {

printf("Sending RARP request for MAC: %s\n", mac);

// Search for IP address in the devices array

int i;

for (i = 0; i < numDevices; i++) {

if (strcmp(devices[i].mac, mac) == 0) {

printf("RARP reply received! IP address: %s\n", devices[i].ip);

return;

printf("RARP request failed. MAC address not found.\n");

int main() {

// Add some devices to the simulation

strcpy(devices[0].ip, "192.168.0.1");

strcpy(devices[0].mac, "00:11:22:33:44:55");

numDevices++;

strcpy(devices[1].ip, "192.168.0.2");

strcpy(devices[1].mac, "AA:BB:CC:DD:EE:FF");

numDevices++;

// Send ARP request

sendARPRequest("192.168.0.1");

// Send RARP request


sendRARPRequest("AA:BB:CC:DD:EE:FF");

return 0;

In this code, we define a Device structure that holds the IP address and MAC address of a device. We create an array
devices to store the simulated devices. The sendARPRequest function simulates sending an ARP request for a given
IP address and searches for a matching MAC address in the devices array. Similarly, the sendRARPRequest function
simulates sending a RARP request for a given MAC address and searches for a matching IP address in the devices
array.

In the main function, we add two devices to the simulation and then demonstrate sending an ARP request and a
RARP request. Note that this is a simplified simulation and doesn't include all the complexities of a real ARP/RARP
implementation.

2. Write a code simulating PING and TRACEROUTE command in c.

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

#include <string.h>

#include <unistd.h>

#include <arpa/inet.h>

#include <netinet/ip_icmp.h>

#include <netinet/ip.h>

#include <sys/socket.h>

#include <sys/types.h>

#include <sys/time.h>

#define PACKET_SIZE 64

#define MAX_HOPS 30

#define MAX_RETRIES 3

#define TIMEOUT 1

// Calculate the Internet Checksum (RFC 1071)


unsigned short calculateChecksum(unsigned short* buffer, int length) {

unsigned long sum = 0;

while (length > 1) {

sum += *buffer++;

length -= 2;

if (length == 1) {

sum += *(unsigned char*)buffer;

sum = (sum >> 16) + (sum & 0xFFFF);

sum += (sum >> 16);

return (unsigned short)(~sum);

// Send an ICMP Echo Request packet

void sendPingRequest(int sockfd, struct sockaddr_in* dest_addr, int seq_num) {

char packet[PACKET_SIZE];

struct icmp* icmp_hdr = (struct icmp*)packet;

memset(packet, 0, sizeof(packet));

icmp_hdr->icmp_type = ICMP_ECHO;

icmp_hdr->icmp_code = 0;

icmp_hdr->icmp_id = getpid();

icmp_hdr->icmp_seq = seq_num;

icmp_hdr->icmp_cksum = 0;

icmp_hdr->icmp_cksum = calculateChecksum((unsigned short*)icmp_hdr, PACKET_SIZE);


if (sendto(sockfd, packet, sizeof(packet), 0, (struct sockaddr*)dest_addr, sizeof(struct sockaddr)) == -1) {

perror("sendto");

exit(1);

// Receive ICMP Echo Reply packets

int receivePingReply(int sockfd, struct sockaddr_in* src_addr, int seq_num) {

char buffer[PACKET_SIZE];

socklen_t addrlen = sizeof(struct sockaddr);

struct ip* ip_hdr;

struct icmp* icmp_hdr;

while (1) {

if (recvfrom(sockfd, buffer, sizeof(buffer), 0, (struct sockaddr*)src_addr, &addrlen) == -1) {

perror("recvfrom");

exit(1);

ip_hdr = (struct ip*)buffer;

icmp_hdr = (struct icmp*)(buffer + (ip_hdr->ip_hl << 2));

if (icmp_hdr->icmp_type == ICMP_ECHOREPLY && icmp_hdr->icmp_id == getpid() && icmp_hdr->icmp_seq


== seq_num) {

return 1; // Echo reply received

} else if (icmp_hdr->icmp_type == ICMP_TIME_EXCEEDED) {

return 0; // TTL expired

}
}

// Send ICMP Echo Request packets with increasing TTL

void sendTracerouteRequest(const char* dest_ip) {

int sockfd = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);

if (sockfd == -1) {

perror("socket");

exit(1);

struct sockaddr_in dest_addr;

memset(&dest_addr, 0, sizeof(struct sockaddr_in));

dest_addr.sin_family = AF_INET;

dest_addr.sin_addr.s_addr = inet_addr(dest_ip);

int ttl;

for (ttl = 1; ttl <= MAX_HOPS; ttl++) {

setsockopt(sockfd, IPPROTO_IP, IP_TTL, &ttl, sizeof(int));

struct timeval start_time, end_time;

gettimeofday(&start_time, NULL);

int retry;

for (retry = 0; retry < MAX_RETRIES; retry++) {

sendPingRequest(sockfd, &dest_addr, ttl);

if (receivePingReply(sockfd, &dest_addr, ttl)) {

gettimeofday(&end_time, NULL);

double elapsed_time = (double)(end_time.tv_sec - start_time.tv_sec) +


(double)(end_time.tv_usec - start_time.tv_usec) / 1000000.0;

printf("%d\t%s\t%f ms\n", ttl, inet_ntoa(dest_addr.sin_addr), elapsed_time * 1000);

break;

if (retry == MAX_RETRIES) {

printf("%d\t*\n", ttl);

if (ttl == MAX_HOPS || inet_ntoa(dest_addr.sin_addr) == inet_ntoa(dest_addr.sin_addr)) {

break;

close(sockfd);

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

if (argc != 2) {

printf("Usage: %s <destination_ip>\n", argv[0]);

return 1;

const char* dest_ip = argv[1];

printf("PING %s:\n\n", dest_ip);

sendTracerouteRequest(dest_ip);
return 0;

In this code, we use sockets to send ICMP Echo Request packets and receive ICMP Echo Reply
packets to simulate the ping and traceroute commands.

The sendPingRequest function constructs and sends an ICMP Echo Request packet to the
destination IP address specified. The receivePingReply function receives ICMP Echo Reply packets
and checks if they match the expected sequence number.

The sendTracerouteRequest function sends a series of ICMP Echo Request packets with increasing
TTL (Time-to-Live) values to simulate the traceroute command. It sets the TTL for each packet,
sends it, and waits for the corresponding ICMP Echo Reply or TTL expired message. The elapsed
time is calculated for each successful reply and printed to the console.

In the main function, we specify the destination IP address as a command-line argument and call
the sendTracerouteRequest function to initiate the traceroute simulation.

3. Write a program to implement RPC (remote procedure call) in c.

This example focuses on a simple client-server architecture where the client makes a remote
procedure call to the server.

First, let's define the interface for the remote procedure. We'll use a basic arithmetic operation
as an example:

// rpc_interface.h

#ifndef RPC_INTERFACE_H

#define RPC_INTERFACE_H

int add(int a, int b);


#endif

Next, we'll implement the server code that provides the remote procedure:

// rpc_server.c

#include "rpc_interface.h"

#include <stdio.h>

int add(int a, int b) {

return a + b;

int main() {

// Start the server and wait for remote procedure calls

return 0;

Now, let's implement the client code that makes a remote procedure call to the server:

// rpc_client.c

#include "rpc_interface.h"

#include <stdio.h>

#include <rpc/rpc.h>
int main() {

// Create a client handle to connect to the server

CLIENT *cl;

cl = clnt_create("localhost", RPC_INTERFACE, RPC_VERSION, "tcp");

if (cl == NULL) {

clnt_pcreateerror("Error creating client handle");

return 1;

// Make the remote procedure call

int a = 5;

int b = 3;

int result = add_1(&a, &b, cl);

if (result == -1) {

clnt_perror(cl, "Remote procedure call failed");

return 1;

// Print the result

printf("Result: %d\n", result);

// Destroy the client handle


clnt_destroy(cl);

return 0;

To compile and run the RPC example, follow these steps:

Compile the server code:

gcc rpc_server.c -o server -lnsl

Compile the client code:

gcc rpc_client.c -o client -lnsl

Start the server in one terminal window:

./server

Run the client in another terminal window:

./client

This is a simplified example of RPC in C using the RPC library. However, in real-world
scenarios, implementing a robust and secure RPC system requires additional considerations
such as serialization/deserialization, error handling, authentication, and transport protocols.
It's important to refer to the appropriate documentation and libraries for a complete and
production-ready RPC implementation.

4. Write a c program to find IP address, subnet mask and default gateway.

To find the IP address, subnet mask, and default gateway in C, you can use system commands
to execute shell commands that retrieve this information from the operating system.

#include <stdio.h>

#include <stdlib.h>
#define MAX_COMMAND_LENGTH 100

int main() {

char command[MAX_COMMAND_LENGTH];

char result[MAX_COMMAND_LENGTH];

// Get IP address

sprintf(command, "ipconfig | grep \"IPv4 Address\" | awk '{print $NF}'");

FILE* ip_output = popen(command, "r");

if (ip_output == NULL) {

printf("Failed to get IP address.\n");

return 1;

fgets(result, sizeof(result), ip_output);

printf("IP Address: %s", result);

pclose(ip_output);

// Get subnet mask

sprintf(command, "ipconfig | grep \"Subnet Mask\" | awk '{print $NF}'");


FILE* subnet_output = popen(command, "r");

if (subnet_output == NULL) {

printf("Failed to get subnet mask.\n");

return 1;

fgets(result, sizeof(result), subnet_output);

printf("Subnet Mask: %s", result);

pclose(subnet_output);

// Get default gateway

sprintf(command, "ipconfig | grep \"Default Gateway\" | awk '{print $NF}'");

FILE* gateway_output = popen(command, "r");

if (gateway_output == NULL) {

printf("Failed to get default gateway.\n");

return 1;

fgets(result, sizeof(result), gateway_output);

printf("Default Gateway: %s", result);


pclose(gateway_output);

return 0;

In this code, we use the ipconfig command (for Windows) to retrieve the IP address, subnet
mask, and default gateway information. We pipe the output to grep and awk commands to
extract the specific values we need. The popen function allows us to execute the shell command
and read its output.

5. Write a c program to find IP address, subnet mask and default gateway.

A C program that demonstrates socket programming using UDP and TCP for various purposes:

1. Simple DNS Client/Server:


• The client sends a domain name to the server.
• The server resolves the domain name and sends back the corresponding IP address
to the client.
2. Date and Time Client/Server:
• The client requests the current date and time from the server.
• The server retrieves the current date and time and sends it back to the client.
3. Echo Client/Server:
• The client sends a message to the server.
• The server receives the message and echoes it back to the client.
4. Iterative Server:
• The server handles one client connection at a time.
• After completing the communication with one client, it moves on to the next client.
5. Concurrent Server:
• The server handles multiple client connections concurrently using multithreading.
• Each client connection is assigned a separate thread to communicate with the
server.
// DNS Server
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>

#define SERVER_PORT 53
#define MAX_BUFFER_SIZE 1024

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

sockfd = socket(AF_INET, SOCK_DGRAM, 0);

if (sockfd < 0) {
perror("Socket creation failed");
exit(1);
}

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

server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(SERVER_PORT);
server_addr.sin_addr.s_addr = INADDR_ANY;

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


perror("Binding failed");
exit(1);
}

printf("DNS Server listening on port %d\n", SERVER_PORT);

while (1) {
socklen_t client_len = sizeof(client_addr);
ssize_t num_bytes = recvfrom(sockfd, buffer, sizeof(buffer), 0, (struct sockaddr*)&client_addr,
&client_len);

if (num_bytes < 0) {
perror("Error receiving data");
exit(1);
}

buffer[num_bytes] = '\0';

// Perform DNS lookup and obtain IP address based on the received domain name
// Send IP address to the client
sendto(sockfd, ip_address, strlen(ip_address), 0, (struct sockaddr*)&client_addr, client_len);
}

close(sockfd);

return 0;
}

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

#define SERVER_IP "127.0.0.1"


#define SERVER_PORT 53
#define MAX_BUFFER_SIZE 1024

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

sockfd = socket(AF_INET, SOCK_DGRAM, 0);

if (sockfd < 0) {
perror("Socket creation failed");
exit(1);
}

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

server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(SERVER_PORT);
server_addr.sin_addr.s_addr = inet_addr(SERVER_IP);

printf("Enter domain name: ");


fgets(domain_name, sizeof(domain_name), stdin);

size_t domain_len = strlen(domain_name);


if (domain_len > 0 && domain_name[domain_len - 1] == '\n') {
domain_name[domain_len - 1] = '\0'; // Remove newline character
}

sendto(sockfd, domain_name, strlen(domain_name), 0, (struct sockaddr*)&server_addr,


sizeof(server_addr));

ssize_t num_bytes = recvfrom(sockfd, buffer, sizeof(buffer), 0, NULL, NULL);

if (num_bytes < 0) {
perror("Error receiving data");
exit(1);
}

buffer[num_bytes] = '\0';

printf("Resolved IP address: %s\n", buffer);

close(sockfd);

return 0;
}

The code provided above demonstrates a simple DNS client and server using UDP. To implement the other
examples (Date and Time, Echo, Iterative, and Concurrent), you can refer to the relevant resources and
adapt the code accordingly.

You might also like