Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

CNS Lab Manual

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

1.

Study of basic Network commands and Network configuration


commands.
BASIC NETWORK COMMANDS :
Basic network commands are specific instructions or commands that are used to manage,
diagnose, and troubleshoot computer networks. These commands are typically run in a
command-line interface (CLI) or terminal window. They allow network administrators and
users to interact with network devices, gather information about network connectivity, and
perform various tasks related to network configuration and monitoring. Here are some
commonly used basic network commands:
1. ping :
Sends ICMP (Internet Control Message Protocol) echo requests to a specific IP address or
hostname to test network connectivity and measure round-trip time.
For example:
ping google.com
2. ipconfig (Windows) / ifconfig (Unix-like systems) :
Displays the IP configuration information for the network interfaces on the system, including
IP addresses, subnet masks, and gateway addresses.
For example:
ipconfig /all (Windows)
ifconfig (Unix-like)
3. nslookup (Windows) / dig (Unix-like systems) :
Performs DNS (Domain Name System) queries to retrieve information about domain names,
such as IP addresses and DNS records. For example:
```
nslookup google.com (Windows)
dig google.com (Unix-like)
```
4. tracert (Windows) / traceroute (Unix-like systems):
Traces the route that packets take from the local system to a remote destination, showing the
IP addresses of intermediate routers along the way.
For example:
tracert google.com (Windows)
traceroute google.com (Unix-like)
5. netstat:
Displays information about network connections, routing tables, interface statistics, and
network protocols. It can help diagnose network-related issues and monitor network activity.
For example:
netstat -an
6. ifconfig (deprecated on many systems):
Configures and displays network interface information, including IP addresses, netmasks, and
network interfaces' operational states.
For example:
ifconfig eth0 192.168.1.2 netmask 255.255.255.0 up (Unix-like)
7. route:
Displays and manipulates the system's IP routing table, allowing you to configure static
routes or view the current routing configuration.
For example:
route -n (Unix-like)
8. arp:
Displays and manipulates the ARP (Address Resolution Protocol) cache, which maps IP
addresses to MAC addresses on a local network.
For example:
arp -a (Windows)
arp -n (Unix-like)
9. ssh:
Initiates a secure shell session to connect to a remote server or device over a network
securely.
For example:
ssh username@hostname
10. ftp:
Initiates a File Transfer Protocol (FTP) session to transfer files between computers on a
network.
For example:
ftp hostname
These are just a few examples of basic network commands. They provide essential tools for
managing and troubleshooting networks, helping administrators ensure smooth network
operations and diagnose connectivity issues. The commands might vary based on the
operating system we are using.
NETWORK CONFIGURATION COMMANDS :
Network configuration commands are specific instructions or commands used to configure
and manage various aspects of computer network settings. These commands are typically run
in a command-line interface (CLI) or terminal window on network devices to set up
parameters such as IP addresses, subnet masks, gateway addresses, DNS settings, and more.
Here are some commonly used network configuration commands:
1. ifconfig (Unix-like systems):
This command configures network interfaces, including assigning IP addresses, subnet
masks, and enabling/disabling interfaces.
For example:
ifconfig eth0 192.168.1.2 netmask 255.255.255.0 up
2. ip address (Unix-like systems):
Similar to ifconfig, this command is part of the iproute2 suite and is used to configure IP
addresses and network interfaces.
For example:
ip address add 192.168.1.2/24 dev eth0
3. netsh (Windows):
The `netsh` command in Windows is used to configure various network settings, including IP
addresses, interfaces, and firewall rules.
For example:
netsh interface ipv4 set address "Local Area Connection" static 192.168.1.2 255.255.255.0
192.168.1.1
4. route (Unix-like systems):
This command is used to add or manipulate IP routing table entries, allowing you to define
how network traffic is directed.
For example:
route add default gw 192.168.1.1
5. ip route (Unix-like systems):
Part of the iproute2 suite, this command is used to manage the routing table and configure
routing settings. For example:
ip route add default via 192.168.1.1
6. ifup/ifdown (Unix-like systems):
These commands are used to bring network interfaces up or down, respectively.
For example:
ifup eth0
ifdown eth0
7. nmcli (Linux):
The Network Manager Command-Line Interface (nmcli) is used to configure and manage
network settings in Linux systems. It provides various options for configuring network
connections
For example:
nmcli connection modify eth0 ipv4.addresses "192.168.1.2/24" ipv4.gateway "192.168.1.1"
8. sysctl (Unix-like systems):
This command is used to configure various kernel parameters, including network-related
settings.
For example, to enable IP forwarding:
sysctl net.ipv4.ip_forward=1
9. ifcfg (Linux):
This refers to configuration files used in many Linux distributions to define network
interfaces and settings.
For example, in Red Hat-based distributions, you would find these files in the
`/etc/sysconfig/network-scripts/` directory.
10. netplan (Linux):
Netplan is used to configure networking in modern Linux distributions, particularly those
using systemd. It involves editing YAML configuration files to set up network settings.
These commands allow administrators to set up and modify network configuration
parameters, ensuring that devices can communicate effectively within a network
environment. The specific commands available and their syntax can vary based on the
operating system and distribution being used.
2. Connect the computers in Local Area Network.
Connecting computers in a Local Area Network (LAN) involves several steps. Here's a
general guide to set up a basic LAN:
1. Choose a Network Topology:
- Decide on the network topology you want to use. Common topologies include star, bus,
ring, and mesh. In home and small office environments, a star topology (all computers
connected to a central device like a router or switch) is most common.
2. Obtain the Necessary Equipment:
- Acquire the necessary hardware such as computers, network cables (Ethernet cables), a
router or switch, and, if needed, network adapters.
3. Set Up the Router or Switch:
- If you're using a router, connect it to your internet modem (if applicable). Connect each
computer to the router using Ethernet cables or connect them to a switch if you're using one.
4. Configure IP Addresses:
- Computers on the same LAN need unique IP addresses. You can use Dynamic Host
Configuration Protocol (DHCP) to automatically assign IP addresses, or you can manually
configure static IP addresses. Most home networks use DHCP.
5. Enable File and Printer Sharing (Optional):
- If you want to share files and printers between computers, enable file and printer sharing
on each device. This is usually done through the operating system's network settings.
6. Workgroup or Domain Configuration (Optional):
- For Windows-based networks, you can create a workgroup or join a domain to simplify
resource sharing and management. This step is optional and may not be necessary for smaller
networks.
7. Test the Connection:
- Ensure that each computer can communicate with others on the network. You can do this
by attempting to ping other computers or access shared files.
8. Firewall Configuration:
- Check and configure firewalls on each computer to allow network traffic as needed.
Firewalls can sometimes block communication between devices on a network.
9. Troubleshooting:
- If you encounter issues, troubleshoot by checking cables, ensuring devices are powered
on, verifying IP configurations, and checking for any firewall issues.
3. Performing an Initial Switch and Router Configuration
Performing an initial configuration for a switch and router typically involves accessing their
command-line interfaces and configuring basic settings. Below are generalized steps for
configuring a Cisco router and switch using the command-line interface (CLI). Keep in mind
that specific commands and procedures may vary depending on the models and software
versions you are using.
Initial Router Configuration:
1. Access the Router:
- Connect to the router using a console cable and a terminal emulation program like PuTTY
or HyperTerminal.
2. Enter Privileged EXEC Mode:
- Type `enable` and press Enter.
3. Enter Global Configuration Mode:
- Type `configure terminal` or `conf t` and press Enter.
4. Set the Hostname:
- In global configuration mode, type `hostname YourRouterName` to set the router's
hostname.
5. Configure Interfaces:
- Enter interface configuration mode for each interface (e.g., `interface GigabitEthernet0/0`)
and set IP addresses using the `ip address` command.
6. Enable Routing:
- If the router is going to perform routing, enable routing with the `ip routing` command.
7. Set the Default Gateway (if applicable):
- Use the `ip route 0.0.0.0 0.0.0.0 next-hop-ip` command to set the default route.
8. Configure Passwords:
- Set passwords for console and vty lines using `line console 0` and `line vty 0 15`
commands. Use the `password` command.
9. Save Configuration:
- Type `write memory` or `copy running-config startup-config` to save the configuration.

Initial Switch Configuration:


1. Access the Switch:
- Connect to the switch using a console cable and a terminal emulation program.
2. Enter Privileged EXEC Mode:
- Type `enable` and press Enter.
3. Enter Global Configuration Mode:
- Type `configure terminal` or `conf t` and press Enter.
4. Set the Hostname:
- In global configuration mode, type `hostname YourSwitchName` to set the switch's
hostname.
5. Configure Interfaces:
- Enter interface configuration mode for each interface (e.g., `interface GigabitEthernet0/1`)
and set interfaces using the `switchport mode` and `switchport access vlan` commands.
6. Configure VLANs (if needed):
- Use the `vlan` command to create VLANs, and assign switch ports to VLANs in interface
configuration mode.
7. Configure Management Interface (if needed):
- Set the management IP address using the `interface vlan 1` and `ip address` commands.
8. Configure Passwords:
- Set passwords for console and vty lines using `line console 0` and `line vty 0 15`
commands. Use the `password` command.
9. Save Configuration:
- Type `write memory` or `copy running-config startup-config` to save the configuration.
4. Connecting, Configuring and Troubleshooting a Switched Network
Connecting, configuring, and troubleshooting a switched network involves several steps.
Below is a general guide for these tasks. Note that specific commands and procedures can
vary depending on the switch model and software version.
Connecting a Switched Network:
1. Physical Connections:
- Connect the switches using Ethernet cables. Use crossover cables or enable Auto
MDI/MDIX if the switches don't support automatic crossover.
2. Connect End Devices:
- Connect computers, printers, or other devices to the switch ports using Ethernet cables.
3. Power On Devices:
- Power on the switches and end devices.
Configuring a Switched Network:
1. Access the Switch CLI:
- Connect to the switch using a console cable and a terminal emulation program (e.g.,
PuTTY).
2. Enter Privileged EXEC Mode:
- Type `enable` and press Enter.
3. Enter Global Configuration Mode:
- Type `configure terminal` or `conf t` and press Enter.
4. Set the Hostname:
- In global configuration mode, type `hostname SwitchName` to set the switch's hostname.
5. Configure Interfaces:
- Enter interface configuration mode for each interface (e.g., `interface
GigabitEthernet0/1`). Set interfaces using the `switchport mode` and `switchport access vlan`
commands.
6. Configure VLANs (if needed):
- Use the `vlan` command to create VLANs. Assign switch ports to VLANs in interface
configuration mode.
7. Configure Management Interface (if needed):
- Set the management IP address using the `interface vlan 1` and `ip address` commands.
8. Configure Spanning Tree Protocol (STP):
- Enable STP with the `spanning-tree vlan` command. Verify the STP status with `show
spanning-tree`.
9. Configure Port Security (if needed):
- Use the `switchport port-security` command to restrict access to switch ports based on
MAC addresses.
10. Save Configuration:
- Type `write memory` or `copy running-config startup-config` to save the configuration.

Troubleshooting a Switched Network:


1. Check Physical Connections:
- Ensure all cables are securely connected. Look for link and activity lights on the switch
ports.
2. Verify VLAN Configurations:
- Confirm that VLAN assignments are correct on switch ports and that VLANs match
between connected switches.
3. Check STP Status:
- Verify STP status using the `show spanning-tree` command. Resolve any STP-related
issues, such as blocked ports.
4. Verify IP Configurations:
- Check IP configurations on management interfaces to ensure connectivity for remote
management.
5. Test Connectivity:
- Use the `ping` command to test connectivity between devices within the same VLAN and
across VLANs.
6. Check Port Security Status (if configured):
- Verify the port security configuration using the `show port-security` command.
7. Review Logs:
- Check switch logs (`show logging` or `show log`) for any error messages or unusual
activities.
8. Update Firmware (if needed):
- Check if there are firmware updates for the switch and update if necessary.
Remember to consult the specific documentation for your switch model and software version
for detailed commands and troubleshooting procedures.
5. Implementation of Error Detection / Error Correction Techniques

#include <stdio.h>
void generateHammingCode(int data[], int m, int r) {
int hammingCode[m + r];
int i, j, parityBitPosition = 0;

// Initialize Hamming Code with 0


for (i = 1, j = 0; i <= m + r; i++) {
if ((i & (i - 1)) != 0) {
hammingCode[i - 1] = data[j++];
} else {
hammingCode[i - 1] = 0;
parityBitPosition++;
}
}

// Calculate parity bits


for (i = 0; i < r; i++) {
for (j = 0; j < m + r; j++) {
if (((j + 1) & (1 << i)) && hammingCode[j]) {
hammingCode[parityBitPosition - 1] ^= hammingCode[j];
}
}
parityBitPosition <<= 1;
}

// Display Hamming Code


printf("Hamming Code: ");
for (i = 0; i < m + r; i++) {
printf("%d ", hammingCode[i]);
}
printf("\n");
}

int main() {
int m, r;

// Input data size (m) and number of redundant bits (r)


printf("Enter data size (m): ");
scanf("%d", &m);
printf("Enter number of redundant bits (r): ");
scanf("%d", &r);

// Input data
int data[m];
printf("Enter data (bit by bit): ");
for (int i = 0; i < m; i++) {
scanf("%d", &data[i]);
}
// Generate and display Hamming Code
generateHammingCode(data, m, r);
return 0;
}

OUTPUT :
Enter data size (m): 4
Enter number of redundant bits (r): 3
Enter data (bit by bit): 1 0 1 1
Hamming Code: 1 0 1 1 0 1 1 1
6. Implementation of Stop and Wait Protocol and sliding window

Stop-and-Wait Protocol:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define FRAME_SIZE 4

// Function to simulate the Stop-and-Wait protocol


void stopAndWait(int frames[], int frameCount) {
int i;
printf("Sender\tReceiver\n");
for (i = 0; i < frameCount; i++) {
// Send frame
printf("%d\t-\n", frames[i]);
// Simulate transmission delay
printf("Transmission...\n");
usleep(200000); // Simulate 200ms delay

// Simulate acknowledgment delay


int acknowledge = rand() % 2; // Simulating a random acknowledgment (0 for NAK, 1
for ACK)
if (acknowledge) {
// Receive frame
printf("-\t%d\n", frames[i]);
// Simulate processing delay
printf("Processing...\n");
// Acknowledge receipt
printf("Acknowledge %d\n", i + 1);
} else {
printf("NAK received, Resending %d\n", frames[i]);
i--; // Resend the same frame
}
printf("\n");
}
}

int main() {
int frames[FRAME_SIZE] = {1, 2, 3, 4};
// Simulate Stop-and-Wait protocol
stopAndWait(frames, FRAME_SIZE);
return 0;
}

Output :
Sender Receiver
1 -
Transmission...
- 1
Processing...
Acknowledge 1

2 -
Transmission...
- 2
Processing...
Acknowledge 2

3 -
Transmission...
NAK received, Resending 3
3 -
Transmission...
- 3
Processing...
Acknowledge 3

4 -
Transmission...
- 4
Processing...
Acknowledge 4

Sliding Window Protocol:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define WINDOW_SIZE 3

// Function to simulate the Sliding Window protocol


void slidingWindow(int frames[], int frameCount) {
int senderIndex = 0, receiverIndex = 0;
printf("Sender\tReceiver\n");
while (receiverIndex < frameCount) {
// Send frames
for (int i = 0; i < WINDOW_SIZE && senderIndex < frameCount; i++) {
printf("%d\t-\n", frames[senderIndex]);
senderIndex++;
}
// Simulate transmission delay
printf("Transmission...\n");
usleep(200000); // Simulate 200ms delay
// Simulate acknowledgment delay
int acknowledge = rand() % 2; // Simulating a random acknowledgment (0 for NAK, 1
for ACK)
if (acknowledge) {
// Receive frames
for (int i = 0; i < WINDOW_SIZE && receiverIndex < frameCount; i++) {
printf("-\t%d\n", frames[receiverIndex]);
receiverIndex++;
// Simulate processing delay
printf("Processing...\n");
}
// Acknowledge receipt
printf("Acknowledge %d\n", receiverIndex);
} else {
printf("NAK received, Resending frames\n");
senderIndex = receiverIndex; // Resend frames from the last acknowledged frame
}
printf("\n");
}
}

int main() {
int frames[FRAME_SIZE] = {1, 2, 3, 4};

// Simulate Sliding Window protocol


slidingWindow(frames, FRAME_SIZE);
return 0;
}
Output :
Sender Receiver
1 -
Transmission...
- 1
Processing...
2 -
Transmission...
- 2
Processing...
3 -
Transmission...
- 3
Processing...
Acknowledge 3

4 -
Transmission...
- 4
Processing...
Acknowledge 4
7. Implementation and study of Goback-N and selective repeat protocols

Go-Back-N Protocol:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define WINDOW_SIZE 3
#define FRAME_SIZE 5

// Function to simulate the Go-Back-N protocol


void goBackN(int frames[], int frameCount) {
int senderIndex = 0, receiverIndex = 0;
printf("Sender\tReceiver\n");
while (receiverIndex < frameCount) {
// Send frames within the window
for (int i = 0; i < WINDOW_SIZE && senderIndex < frameCount; i++) {
printf("%d\t-\n", frames[senderIndex]);
senderIndex++;
}

// Simulate transmission delay


printf("Transmission...\n");
usleep(200000); // Simulate 200ms delay
// Simulate acknowledgment delay
int acknowledge = rand() % 2; // Simulating a random acknowledgment (0 for NAK, 1
for ACK)
if (acknowledge) {
// Receive frames
for (int i = 0; i < WINDOW_SIZE && receiverIndex < frameCount; i++) {
printf("-\t%d\n", frames[receiverIndex]);
receiverIndex++;
// Simulate processing delay
printf("Processing...\n");
}

// Acknowledge receipt
printf("Acknowledge %d\n", receiverIndex);
} else {
printf("NAK received, Resending frames\n");
senderIndex = receiverIndex; // Go back to the first unacknowledged frame
}
printf("\n");
}
}

int main() {
int frames[FRAME_SIZE] = {1, 2, 3, 4, 5};
// Simulate Go-Back-N protocol
goBackN(frames, FRAME_SIZE);
return 0;
}

Output :
Sender Receiver
1 -
Transmission...
- 1
Processing...
2 -
Transmission...
- 2
Processing...
3 -
Transmission...
- 3
Processing...
Acknowledge 3

4 -
Transmission...
- 4
Processing...
Acknowledge 4

5 -
Transmission...
- 5
Processing...
Acknowledge 5

Selective Repeat Protocol:


#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define WINDOW_SIZE 3
#define FRAME_SIZE 5

// Function to simulate the Selective Repeat protocol


void selectiveRepeat(int frames[], int frameCount) {
int senderIndex = 0, receiverIndex = 0;
printf("Sender\tReceiver\n");
while (receiverIndex < frameCount) {
// Send frames within the window
for (int i = 0; i < WINDOW_SIZE && senderIndex < frameCount; i++) {
printf("%d\t-\n", frames[senderIndex]);
senderIndex++;
}

// Simulate transmission delay


printf("Transmission...\n");
usleep(200000); // Simulate 200ms delay

// Simulate acknowledgment delay


int acknowledge[WINDOW_SIZE]; // Array to store acknowledgment status for each
frame
for (int i = 0; i < WINDOW_SIZE; i++) {
acknowledge[i] = rand() % 2; // Simulating random acknowledgments
}

// Receive frames
for (int i = 0; i < WINDOW_SIZE && receiverIndex < frameCount; i++) {
if (acknowledge[i]) {
printf("-\t%d\n", frames[receiverIndex]);
receiverIndex++;

// Simulate processing delay


printf("Processing...\n");
} else {
printf("NAK received for frame %d, Resending frame %d\n", receiverIndex,
receiverIndex);
}
}
printf("Acknowledge Status: ");
for (int i = 0; i < WINDOW_SIZE; i++) {
printf("%d ", acknowledge[i]);
}
printf("\n\n");
}
}

int main() {
int frames[FRAME_SIZE] = {1, 2, 3, 4, 5};
// Simulate Selective Repeat protocol
selectiveRepeat(frames, FRAME_SIZE);
return 0;
}

Output :
Sender Receiver
1 -
Transmission...
- 1
Processing...
2 -
Transmission...
- 2
Processing...
3 -
Transmission...
- 3
Processing...
Acknowledge Status: 1 1 1

4 -
Transmission...
- 4
Processing...
Acknowledge Status: 0 1 1
NAK received for frame 4, Resending frame 4

4 -
Transmission...
- 4
Processing...
Acknowledge Status: 1 1 1

5 -
Transmission...
- 5
Processing...
Acknowledge Status: 0 0 1
NAK received for frame 5, Resending frame 5

5 -
Transmission...
- 5
Processing...
Acknowledge Status: 1 1 1
8. Implementation of High Level Data Link Control
#include <stdio.h>
#include <string.h>
// HDLC Frame structure
struct HDLCFrame {
char delimiter;
char data[100];
short fcs; // Frame Check Sequence (Checksum)
};

// Function to calculate the Frame Check Sequence (FCS)


short calculateFCS(const char *data) {
short fcs = 0;
for (int i = 0; i < strlen(data); i++) {
fcs ^= data[i];
for (int j = 0; j < 8; j++) {
if (fcs & 0x01) {
fcs = (fcs >> 1) ^ 0x8408;
} else {
fcs >>= 1;
}
}
}
return fcs;
}

// Function to send data using HDLC framing


void sendHDLC(const char *data) {
struct HDLCFrame frame;
// HDLC frame delimiter
frame.delimiter = 0x7E;

// Copy data to frame


strcpy(frame.data, data);

// Calculate FCS
frame.fcs = calculateFCS(data);

// Print the HDLC frame


printf("Sent HDLC Frame:\n");
printf("Delimiter: 0x%X\n", frame.delimiter);
printf("Data: %s\n", frame.data);
printf("FCS: 0x%X\n", frame.fcs);
printf("\n");
}

// Function to receive data using HDLC framing


void receiveHDLC(struct HDLCFrame frame) {
// Calculate FCS for received data
short receivedFCS = calculateFCS(frame.data);

// Print the received HDLC frame


printf("Received HDLC Frame:\n");
printf("Delimiter: 0x%X\n", frame.delimiter);
printf("Data: %s\n", frame.data);
printf("Received FCS: 0x%X\n", receivedFCS);

// Check if FCS matches


if (receivedFCS == frame.fcs) {
printf("FCS Match: Frame is error-free.\n");
} else {
printf("FCS Mismatch: Frame may have errors.\n");
}
}

int main() {
const char *dataToSend = "Hello, HDLC!";

// Send data using HDLC framing


sendHDLC(dataToSend);

// Simulate receiving the frame


struct HDLCFrame receivedFrame;
receivedFrame.delimiter = 0x7E;
strcpy(receivedFrame.data, "Hello, HDLC!");
receivedFrame.fcs = calculateFCS(receivedFrame.data);

// Receive data using HDLC framing


receiveHDLC(receivedFrame);
return 0;
}

Output:
Sent HDLC Frame:
Delimiter: 0x7E
Data: Hello, HDLC!
FCS: 0x67DA

Received HDLC Frame:


Delimiter: 0x7E
Data: Hello, HDLC!
Received FCS: 0x67DA
FCS Match: Frame is error-free.
9. Implementation of Link state routing algorithm

#include <stdio.h>
#include <limits.h>
#define MAX_NODES 10

// Structure to represent a node in the network


struct Node {
int cost[MAX_NODES]; // Link costs to other nodes
int shortestPath[MAX_NODES]; // Shortest paths to other nodes
int visited;
};

// Function to initialize a node


void initializeNode(struct Node *node, int nodeCount) {
for (int i = 0; i < nodeCount; i++) {
node->cost[i] = (i == 0) ? 0 : INT_MAX; // Cost to itself is 0, other costs are initially
set to infinity
node->shortestPath[i] = -1; // -1 represents undefined/unknown path
}
node->visited = 0;
}

// Function to find the next node to visit based on the current costs
int findNextNode(struct Node *node, int nodeCount) {
int minCost = INT_MAX;
int nextNode = -1;

for (int i = 0; i < nodeCount; i++) {


if (!node[i].visited && node[i].cost[i] < minCost) {
minCost = node[i].cost[i];
nextNode = i;
}
}

return nextNode;
}

// Function to update costs and paths after visiting a node


void updateCosts(struct Node *node, int currentNode, int nodeCount) {
for (int i = 0; i < nodeCount; i++) {
if (!node[i].visited) {
int newCost = node[currentNode].cost[i] + node[currentNode].cost[currentNode];
if (newCost < node[i].cost[i]) {
node[i].cost[i] = newCost;
node[i].shortestPath[i] = currentNode;
}
}
}
}

// Function to perform Dijkstra's algorithm for Link State Routing


void linkStateRouting(struct Node *network, int nodeCount) {
int currentNode;

for (int step = 0; step < nodeCount; step++) {


// Find the next node to visit
currentNode = findNextNode(network, nodeCount);
if (currentNode == -1) {
// All nodes are visited
break;
}

// Mark the current node as visited


network[currentNode].visited = 1;

// Update costs and paths based on the current node


updateCosts(network, currentNode, nodeCount);
}
}

// Function to print the routing table for a node


void printRoutingTable(struct Node *node, int nodeIndex, int nodeCount) {
printf("Routing Table for Node %d:\n", nodeIndex);
printf("Destination\tCost\tNext Hop\n");

for (int i = 0; i < nodeCount; i++) {


if (i != nodeIndex) {
printf("%d\t\t%d\t%d\n", i, node[nodeIndex].cost[i],
node[nodeIndex].shortestPath[i]);
}
}
printf("\n");
}

int main() {
int nodeCount;
printf("Enter the number of nodes: ");
scanf("%d", &nodeCount);

struct Node network[MAX_NODES];


// Initialize nodes
for (int i = 0; i < nodeCount; i++) {
initializeNode(&network[i], nodeCount);
}

// Input link costs (edges)


for (int i = 0; i < nodeCount; i++) {
for (int j = 0; j < nodeCount; j++) {
if (i != j) {
printf("Enter cost from Node %d to Node %d (or -1 if no direct link): ", i, j);
scanf("%d", &network[i].cost[j]);
}
}
}

// Perform Link State Routing algorithm


linkStateRouting(network, nodeCount);

// Print routing tables for all nodes


for (int i = 0; i < nodeCount; i++) {
printRoutingTable(network, i, nodeCount);
}

return 0;
}

OUTPUT :
Enter the number of nodes: 3
Enter cost from Node 0 to Node 1 (or -1 if no direct link): 2
Enter cost from Node 0 to Node 2 (or -1 if no direct link): -1
Enter cost from Node 1 to Node 0 (or -1 if no direct link): 2
Enter cost from Node 1 to Node 2 (or -1 if no direct link): 1
Enter cost from Node 2 to Node 0 (or -1 if no direct link): -1
Enter cost from Node 2 to Node 1 (or -1 if no direct link): 1

Routing Table for Node 0:


Destination Cost Next Hop
1 2 0
2 3 1

Routing Table for Node 1:


Destination Cost Next Hop
0 2 1
2 1 1

Routing Table for Node 2:


Destination Cost Next Hop
0 3 1
1 1 2
10. Implement the data link layer framing methods such as character,
character-stuffing and bitstuffing.

1. Character Stuffing:
#include<stdio.h>
#include<string.h>
void main()
{
char a[30], fs[50] = " ", t[3], sd, ed, x[3], s[3], d[3], y[3];
int i, j, p = 0, q = 0;
clrscr();
printf("Enter characters to be stuffed:");
scanf("%s", a);
printf("\nEnter a character that represents starting delimiter:");
scanf(" %c", &sd);
printf("\nEnter a character that represents ending delimiter:");
scanf(" %c", &ed);
x[0] = s[0] = s[1] = sd;
x[1] = s[2] = '\0';
y[0] = d[0] = d[1] = ed;
d[2] = y[1] = '\0';
strcat(fs, x);
for(i = 0; i < strlen(a); i++)
{
t[0] = a[i];
t[1] = '\0';
if(t[0] == sd)
strcat(fs, s);
else if(t[0] == ed)
strcat(fs, d);
else
strcat(fs, t);
}
strcat(fs, y);
printf("\n After stuffing:%s", fs);
getch();
}
Output:-
Enter characters to be stuffed: goodday
Enter a character that represents starting delimiter: d
Enter a character that represents ending delimiter: g
After stuffing: dggooddddayg.

2. Bit Stuffing:
#include<stdio.h>
#include<string.h>
int main()
{
int a[20],b[30],i,j,k,count,n;
printf("Enter frame size (Example: 8):");
scanf("%d",&n);
printf("Enter the frame in the form of 0 and 1 :");
for(i=0; i<n; i++)
scanf("%d",&a[i]);
i=0;
count=1;
j=0;
while(i<n)
{
if(a[i]==1)
{
b[j]=a[i];
for(k=i+1; a[k]==1 && k<n && count<5; k++)
{
j++;
b[j]=a[k];
count++;
if(count==5)
{
j++;
b[j]=0;
}
i=k;
}
}
else b[j]=a[i];
i++;
j++;
}
printf("After Bit Stuffing :");
for(i=0; i<j; i++)
printf("%d",b[i]);
return 0;
}
OUTPUT for BIT STUFFING:
Enter frame size (Example: 8):12
Enter the frame in the form of 0 and 1 :0 1 0 1 1 1 1 1 1 0 0 1
After Bit Stuffing :0101111101001
11. Write a program to compute CRC code for the polynomials CRC-12,
CRC-16 and CRC CCIP
#include<stdio.h>
#include<string.h>
#define N strlen(g)
char t[28],cs[28],g[]="10001000000100001";
int a,i,j;
void xor()
{
for(j = 1;j < N; j++)
cs[j] = (( cs[j] == g[j])?'0':'1');
}
void crc()
{
for(i=0;i<N;i++)
cs[i]=t[i];
do
{
if(cs[0]=='1')
xor();
for(j=0;j<N-1;j++)
cs[j]=cs[j+1];
cs[j]=t[i++];
}while(i<=a+N-1);
}
int main()
{
printf("\nEnter data : ");
scanf("%s",t);
printf("\n----------------------------------------");
printf("\nGeneratng polynomial : %s",g);
a=strlen(t);
for(i=a;i<a+N-1;i++)
t[i]='0';
printf("\n----------------------------------------");
printf("\nModified data is : %s",t);
printf("\n----------------------------------------");
crc();
printf("\nChecksum is : %s",cs);
for(i=a;i<a+N-1;i++)
t[i]=cs[i-a];
printf("\n----------------------------------------");
printf("\nFinal codeword is : %s",t);
printf("\n----------------------------------------");
printf("\nEnter received message ");
scanf("%s",t);
crc();
for(i=0;(i<N-1) && (cs[i]!='1');i++);
if(i<N-1)
printf("\nError detected\n\n");
else
printf("\nNo error detected\n\n");
printf("\n----------------------------------------\n");
return 0;
}
12. Develop a simple data link layer that performs the flow control using the
sliding window protocol and loss recovery using the Go-Back-N mechanism.

import time
import random
class Frame:
def __init__(self, seq_num, data):
self.seq_num = seq_num
self.data = data

class SimpleDataLinkLayer:
def __init__(self, window_size):
self.window_size = window_size
self.frames = []
self.expected_seq_num = 0
self.sent_seq_num = 0

def send_frame(self, data):


if len(self.frames) < self.window_size:
frame = Frame(self.sent_seq_num, data)
self.frames.append(frame)
print(f"Sending Frame {frame.seq_num}")
self.sent_seq_num += 1
else:
print("Window is full. Waiting for ACKs...")

def receive_frame(self, frame):


if frame.seq_num == self.expected_seq_num:
print(f"Received Frame {frame.seq_num} successfully.")
self.expected_seq_num += 1
while self.frames and self.frames[0].seq_num < self.expected_seq_num:
self.frames.pop(0)
else:
print(f"Received out-of-order frame {frame.seq_num}. Discarding.")

def simulate_network(self):
while True:
if random.random() < 0.8: # Simulating 80% success rate
if random.random() < 0.2: # Simulating 20% packet loss
print("Packet lost.")
else:
if self.frames:
ack_frame = Frame(self.expected_seq_num - 1, None)
print(f"Sending ACK {ack_frame.seq_num}")
else:
ack_frame = Frame(self.expected_seq_num, None)
print(f"Sending ACK {ack_frame.seq_num}")
time.sleep(1) # Simulating network delay
self.receive_frame(ack_frame)
else:
print("Network error. Retransmitting...")
time.sleep(1) # Simulating network delay

def main():
data_link_layer = SimpleDataLinkLayer(window_size=3)

for i in range(10):
data_link_layer.send_frame(f"Data{i}")

data_link_layer.simulate_network()
if __name__ == "__main__":
main()

OUTPUT :
Sending Frame 0
Sending Frame 1
Sending Frame 2
Window is full. Waiting for ACKs...
Window is full. Waiting for ACKs...
Window is full. Waiting for ACKs...
Window is full. Waiting for ACKs...
Window is full. Waiting for ACKs...
Window is full. Waiting for ACKs...
Window is full. Waiting for ACKs...
Sending ACK -1
Received out-of-order frame -1. Discarding.
Sending ACK -1
Received out-of-order frame -1. Discarding.
Sending ACK -1
Received out-of-order frame -1. Discarding.
Sending ACK -1
Received out-of-order frame -1. Discarding.
Sending ACK -1
Received out-of-order frame -1. Discarding.
Network error. Retransmitting...
Network error. Retransmitting...
13. Implement Dijsktra‘s algorithm to compute the shortest path through a
network

#include<stdio.h>
void main()
{
int path[5][5],i,j,min,a[5][5],p,st=1,ed=5,stp,edp,t[5],index;
clrscr();
printf("enter the costmatrix\n");
for(i=1;i<=5;i++)
for(j=1;j<=5;j++)
scanf("%d",&a[i][j]);
printf("enter the paths\n");
scanf("%d",&p);
printf("enter possible paths\n");
for(i=1;i<=p;i++)
for(j=1;j<=5;j++)
scanf("%d",&path[i][j]);
for(i=1;i<=p;i++)
{
t[i]=0;
stp=st;
for(j=1;j<=5;j++)
{
edp=path[i][j+1];
t[i]=t[i]+a[stp][edp];
if(edp==ed) break;
else stp=edp;
}
}
min=t[st];
index=st;
for(i=1;i<=p;i++)
{
if(min>t[i])
{
min=t[i];
index=i;
}
}
printf("minimum costd",min);
printf("\n minimum cost path ");
for(i=1;i<=5;i++)
{
printf("-->%d",path[index][i]);
if(path[index][i]==ed)
break;
}
getch();
}
OUTPUT :
14. Take an example subnet of hosts and obtain a broadcast tree for the
subnet.

#include <stdio.h>
#include <limits.h>
#define MAX_NODES 10

void dijkstra(int graph[MAX_NODES][MAX_NODES], int source, int num_nodes) {


int distance[MAX_NODES];
int visited[MAX_NODES];

for (int i = 0; i < num_nodes; i++) {


distance[i] = INT_MAX;
visited[i] = 0;
}
distance[source] = 0;

// Find shortest path for all nodes


for (int count = 0; count < num_nodes - 1; count++) {
int min_distance = INT_MAX, min_index;

// Pick the minimum distance vertex from the set of vertices not yet processed
for (int v = 0; v < num_nodes; v++) {
if (!visited[v] && distance[v] <= min_distance) {
min_distance = distance[v];
min_index = v;
}
}
visited[min_index] = 1;

// Update the distance value of the neighboring vertices of the picked vertex
for (int v = 0; v < num_nodes; v++) {
if (!visited[v] && graph[min_index][v] && distance[min_index] != INT_MAX &&
distance[min_index] + graph[min_index][v] < distance[v]) {
distance[v] = distance[min_index] + graph[min_index][v];
}
}
}
printf("Broadcast Tree for Subnet:\n");
printf("Node\tDistance from Source\n");
for (int i = 0; i < num_nodes; i++) {
printf("%d\t\t\t%d\n", i, distance[i]);
}
}

int main() {
// Example subnet with distances between nodes
int graph[MAX_NODES][MAX_NODES] = {
{0, 2, 0, 4, 0},
{2, 0, 3, 0, 0},
{0, 3, 0, 1, 4},
{4, 0, 1, 0, 2},
{0, 0, 4, 2, 0}
};
int num_nodes = 5;
int source = 0;

dijkstra(graph, source, num_nodes);


return 0;
}
OUTPUT :
Broadcast Tree for Subnet:
Node Distance from Source
0 0
1 2
2 5
3 4
4 6
15. Implement distance vector routing algorithm for obtaining routing
tables at each node.

#include<stdio.h>
struct node
{
unsigned dist[20];
unsigned from[20];
}rt[10];
int main()
{
int costmat[20][20];
int nodes,i,j,k,count=0;
printf("\nEnter the number of nodes : ");
scanf("%d",&nodes);//Enter the nodes
printf("\nEnter the cost matrix :\n");
for(i=0;i<nodes;i++)
{
for(j=0;j<nodes;j++)
{
scanf("%d",&costmat[i][j]);
costmat[i][i]=0;
rt[i].dist[j]=costmat[i][j];
rt[i].from[j]=j;
}
}
do{
count=0;
for(i=0;i<nodes;i++)
for(j=0;j<nodes;j++)
for(k=0;k<nodes;k++)
if(rt[i].dist[j]>costmat[i][k]+rt[k].dist[j])
{
rt[i].dist[j]=rt[i].dist[k]+rt[k].dist[j];
rt[i].from[j]=k;
count++;
}
}while(count!=0);
for(i=0;i<nodes;i++)
{
printf("\n\n For router %d\n",i+1);
for(j=0;j<nodes;j++)
{
printf("\t\nnode %d via %d Distance %d ",
j+1,rt[i].from[j]+1,rt[i].dist[j]);
}
}
printf("\n\n");
getch();
}
Output:
Enter the number of nodes :
3
Enter the cost matrix :
027
201
710
For router 1
node 1 via 1 Distance 0
node 2 via 2 Distance 2
node 3 via 3 Distance 3
For router 2
node 1 via 1 Distance 2
node 2 via 2 Distance 0
node 3 via 3 Distance 1
For router 3
node 1 via 1 Distance 3
node 2 via 2 Distance 1
node 3 via 3 Distance 0
16. Write a program for congestion control using Leaky bucket algorithm

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define MAX 5
#define LEAK_RATE 1

void leakyBucket(int inputPackets) {


static int bucket = 0;

printf("Incoming packets: %d\n", inputPackets);

// Add incoming packets to the bucket


bucket += inputPackets;

// If the bucket overflows, limit it to the capacity


if (bucket > MAX) {
printf("Bucket overflow! Dropping excess packets.\n");
bucket = MAX;
}

// Process packets in the bucket


int packetsToSend = (bucket < LEAK_RATE) ? bucket : LEAK_RATE;
bucket -= packetsToSend;
printf("Packets sent: %d\n", packetsToSend);
printf("Remaining packets in the bucket: %d\n", bucket);
}
int main()
{
int i;
int numIterations = 10;
for (i = 1; i <= numIterations; ++i) {
printf("\nIteration %d:\n", i);
// Simulate incoming packets
int incomingPackets = rand() % 8;
leakyBucket(incomingPackets);
sleep(1); // Simulate time passing (1 second sleep)
}
return 0;
}

OUTPUT :
Iteration 1:
Incoming packets: 7
Bucket overflow! Dropping excess packets.
Packets sent: 1
Remaining packets in the bucket: 4

Iteration 2:
Incoming packets: 3
Packets sent: 1
Remaining packets in the bucket: 3

Iteration 3:
Incoming packets: 2
Packets sent: 1
Remaining packets in the bucket: 2
17. Do the following using NS2 Simulator
a. NS2 Simulator - Introduction:
NS2, or Network Simulator 2, is a widely used open-source network simulation tool that
facilitates the study and analysis of various networking protocols and scenarios. Developed in
C++ and OTCL (Object-oriented Tool Command Language), NS2 enables researchers,
engineers, and students to simulate and emulate the behaviour of complex networks, both
wired and wireless. With its modular architecture, NS2 supports the integration of custom
protocols and algorithms, making it a versatile platform for testing and validating new
networking concepts. The simulator provides components such as nodes, links, agents, and
applications that can be configured through TCL scripts. NS2's event-driven simulation
model allows users to define and observe discrete events over time, enabling the analysis of
network performance under different conditions. Visualization tools within NS2 aid in
understanding the dynamics of network protocols, making it an indispensable tool in the field
of computer networking research and education.
b. Simulate to Find the Number of Packets Dropped using Python:
Assuming you have an NS2 simulation script that generates a trace file (e.g., `.tr` file), you
can use Python to analyze this file and find the number of dropped packets. For simplicity,
let's assume the trace file contains lines with information about each packet transmission and
reception.
Python Analysis Script (analyze.py):
def analyze_trace_file(trace_file_path):
dropped_packets = 0

with open(trace_file_path, 'r') as trace_file:


for line in trace_file:
# Assuming each line contains information about a packet event
if "d -" in line: # Detects dropped packets
dropped_packets += 1
return dropped_packets

if __name__ == "__main__":
trace_file_path = "output.tr" # Replace with your actual trace file path
dropped_packets = analyze_trace_file(trace_file_path)
print(f"Number of Dropped Packets: {dropped_packets}")
c. Simulate to Find the Number of Packets Dropped by TCP/UDP using Python:
You can extend the Python script to differentiate between TCP and UDP packets by
modifying the conditions within the analysis loop. Adjust the script according to the specifics
of your NS2 simulation output.
Sample Modification for TCP/UDP Differentiation:
def analyze_trace_file(trace_file_path):
dropped_tcp_packets = 0
dropped_udp_packets = 0

with open(trace_file_path, 'r') as trace_file:


for line in trace_file:
# Assuming each line contains information about a packet event
if "d -tcp" in line:
dropped_tcp_packets += 1
elif "d -udp" in line:
dropped_udp_packets += 1

return dropped_tcp_packets, dropped_udp_packets

if __name__ == "__main__":
trace_file_path = "output.tr" # Replace with your actual trace file path
dropped_tcp, dropped_udp = analyze_trace_file(trace_file_path)
print(f"Number of Dropped TCP Packets: {dropped_tcp}")
print(f"Number of Dropped UDP Packets: {dropped_udp}")

d. Simulate to Find the Number of Packets Dropped due to Congestion


import random
class Network:
def __init__(self, buffer_size):
self.buffer_size = buffer_size
self.buffer = []
self.dropped_packets = 0

def send_packet(self):
# Simulate packet arrival
new_packet = random.randint(1, 10)
if len(self.buffer) < self.buffer_size:
self.buffer.append(new_packet)
print(f"Packet {new_packet} sent successfully.")
else:
print(f"Packet {new_packet} dropped due to congestion.")
self.dropped_packets += 1

def simulate_network(self, num_packets):


for _ in range(num_packets):
self.send_packet()

print(f"\nSimulation completed. Packets dropped due to congestion:


{self.dropped_packets}")

# Example usage
buffer_size = 5
num_packets_to_send = 20

network = Network(buffer_size)
network.simulate_network(num_packets_to_send)
e. Simulate to Compare Data Rate& Throughput.

import time
class DataTransferSimulation:
def __init__(self, data_rate_1, data_rate_2):
self.data_rate_1 = data_rate_1 # Data rate for scenario 1 (in Mbps)
self.data_rate_2 = data_rate_2 # Data rate for scenario 2 (in Mbps)

def simulate_data_transfer(self, duration):


data_transferred_1 = 0
data_transferred_2 = 0

start_time = time.time()
end_time = start_time + duration

while time.time() < end_time:


# Simulate data transfer for scenario 1
data_transferred_1 += self.data_rate_1 / 8 # Convert Mbps to MBps

# Simulate data transfer for scenario 2


data_transferred_2 += self.data_rate_2 / 8 # Convert Mbps to MBps

throughput_1 = data_transferred_1 / duration


throughput_2 = data_transferred_2 / duration

print(f"Scenario 1 Data Rate: {self.data_rate_1} Mbps")


print(f"Scenario 1 Throughput: {throughput_1:.2f} MBps\n")

print(f"Scenario 2 Data Rate: {self.data_rate_2} Mbps")


print(f"Scenario 2 Throughput: {throughput_2:.2f} MBps\n")

# Example usage
data_rate_scenario_1 = 10 # Mbps
data_rate_scenario_2 = 5 # Mbps
simulation_duration = 5 # seconds

simulation = DataTransferSimulation(data_rate_scenario_1, data_rate_scenario_2)


simulation.simulate_data_transfer(simulation_duration)

f. Simulate to Plot Congestion for Different Source/Destination

import matplotlib.pyplot as plt


import numpy as np
import random

class NetworkSimulation:
def __init__(self, num_sources, num_destinations):
self.num_sources = num_sources
self.num_destinations = num_destinations
self.congestion_data = np.zeros((num_sources, num_destinations))

def simulate_congestion(self, num_iterations):


for _ in range(num_iterations):
source = random.randint(0, self.num_sources - 1)
destination = random.randint(0, self.num_destinations - 1)
self.congestion_data[source][destination] += 1

def plot_congestion(self):
plt.imshow(self.congestion_data, cmap='viridis', interpolation='nearest')
plt.colorbar(label='Congestion Count')
plt.xlabel('Destination')
plt.ylabel('Source')
plt.title('Congestion Simulation')
plt.show()

# Example usage
num_sources = 5
num_destinations = 5
num_iterations = 100

simulation = NetworkSimulation(num_sources, num_destinations)


simulation.simulate_congestion(num_iterations)
simulation.plot_congestion()

g. Simulate to Determine the Performance with respect to Transmission of Packets

import simpy
import random
class Packet:
def __init__(self, id, size):
self.id = id
self.size = size

def packet_generator(env, num_packets, packet_size, transmission_rate, channel):


for i in range(num_packets):
packet = Packet(i, packet_size)
yield env.timeout(random.expovariate(1/transmission_rate))
env.process(transmit_packet(env, packet, channel))

def transmit_packet(env, packet, channel):


with channel.request() as req:
yield req
yield env.timeout(packet.size / transmission_rate)
print(f"Packet {packet.id} transmitted at time {env.now}")

# Simulation parameters
num_packets = 10
packet_size = 100 # in bits
transmission_rate = 1000 # in bits per second

env = simpy.Environment()
channel = simpy.Resource(env, capacity=1)
env.process(packet_generator(env, num_packets, packet_size, transmission_rate, channel))
env.run()

h. To create scenario and study the performance of network with CSMA/CA protocol
and CSMA/CD protocols
import simpy
import random

class Node:
def __init__(self, env, name, channel):
self.env = env
self.name = name
self.channel = channel
def transmit_packet(self):
print(f"{self.name} is attempting to transmit a packet.")
with self.channel.request() as req:
yield req
print(f"{self.name} is transmitting a packet.")
yield self.env.timeout(random.uniform(0.1, 0.5))
print(f"{self.name} finished transmitting.")

def simulate_csma_ca(env, num_nodes):


channel = simpy.Resource(env, capacity=1)
nodes = [Node(env, f"Node-{i}", channel) for i in range(num_nodes)]

for _ in range(5): # Simulate 5 rounds


for node in nodes:
env.process(node.transmit_packet())
yield env.timeout(1)

env = simpy.Environment()
env.process(simulate_csma_ca(env, num_nodes=3))
env.run()
18. Implement the following executing protocols of Internet in action using
Wireshark Lab.
a. Packet Capture and Observations using Packet Sniffer.

from scapy.all import sniff

def packet_callback(packet):
# Process the packet here
print(packet.show())

# Sniffing packets on the network


sniff(prn=packet_callback, store=0)

b. Explore various aspects of HTTP Protocol.

import http.client

conn = http.client.HTTPSConnection("www.example.com")
conn.request("GET", "/")
response = conn.getresponse()

print(f"HTTP Status: {response.status}")


print(f"Response Headers: {response.getheaders()}")
print(f"Response Data: {response.read().decode()}")

conn.close()

c. Tracing DNS with


pip install dnspython
import dns.resolver

def trace_dns(domain):
answers = dns.resolver.query(domain, 'A')
for answer in answers:
print(f"IP Address for {domain}: {answer.address}")
# Example usage
trace_dns("www.example.com")
d. Analysis and Obtain various parameters-Values for TCP Protocol in action
from scapy.all import sniff, TCP

def tcp_packet_callback(packet):
if packet.haslayer(TCP):
# Process TCP packet
tcp_flags = packet[TCP].flags
src_port = packet[TCP].sport
dest_port = packet[TCP].dport
print(f"TCP Packet - Source Port: {src_port}, Destination Port: {dest_port}, Flags:
{tcp_flags}")

# Sniffing TCP packets on the network


sniff(prn=tcp_packet_callback, store=0, filter="tcp")
19. Introduction to Network Simulator – Packet Tracer

a. Configuration of a Router using Packet Tracer


1. Open Packet Tracer and select the "Router" device from the devices panel.
2. Place the router on the workspace.
3. Connect the router to a switch or another device using appropriate cables.
4. Double-click on the router to open the CLI (Command Line Interface) or the configuration
dialog.
5. Enter the global configuration mode using the command `enable`.
6. Enter the router configuration mode using the command `configure terminal`.
7. Configure the router interfaces, IP addresses, and routing protocols as needed.
8. Save the configuration using the `write memory` command.

b. Network using Packet Tracer


1. Place the devices (routers, switches, PCs) on the workspace.
2. Connect the devices using appropriate cables.
3. Double-click on each device to configure its settings (e.g., IP addresses, subnet masks).
4. Configure routing if necessary.
5. Save the configuration.

c. Implementation of Static Routing using Packet Tracer


1. Connect two or more routers on the workspace.
2. Double-click on a router to enter the configuration.
3. Enter the global configuration mode using the command `enable`.
4. Enter the router configuration mode using the command `configure terminal`.
5. Add static routes using the `ip route` command.
ip route destination_network subnet_mask next_hop_ip_address
6. Save the configuration.

d. Implementation of RIP using Packet Tracer


1. Connect two or more routers on the workspace.
2. Double-click on a router to enter the configuration.
3. Enter the global configuration mode using the command `enable`.
4. Enter the router configuration mode using the command `configure terminal`.
5. Enable RIP routing protocol.
router rip
6. Configure router interfaces to participate in RIP.
network network_address
7. Save the configuration
20. Develop the network application using socket API

a. Write a Socket program for echo

Echo Server (`echo_server.py`):


import socket

def start_echo_server():
host = '127.0.0.1'
port = 12345

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server_socket:


server_socket.bind((host, port))
server_socket.listen()

print(f"Echo server listening on {host}:{port}")

conn, addr = server_socket.accept()


with conn:
print(f"Connected by {addr}")
while True:
data = conn.recv(1024)
if not data:
break
conn.sendall(data)

if __name__ == "__main__":
start_echo_server()

Echo Client (`echo_client.py`):


import socket

def start_echo_client():
host = '127.0.0.1'
port = 12345

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as client_socket:


client_socket.connect((host, port))
message = input("Enter message to send to the server: ")
client_socket.sendall(message.encode())
data = client_socket.recv(1024)

print(f"Received from server: {data.decode()}")


if __name__ == "__main__":
start_echo_client()

b. Write a Socket program for Ping

Ping Server (`ping_server.py`):


import socket

def start_ping_server():
host = '127.0.0.1'
port = 12346

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server_socket:


server_socket.bind((host, port))
server_socket.listen()

print(f"Ping server listening on {host}:{port}")

conn, addr = server_socket.accept()


with conn:
print(f"Connected by {addr}")
while True:
data = conn.recv(1024)
if not data:
break
conn.sendall(b"Pong")

if __name__ == "__main__":
start_ping_server()

Ping Client (`ping_client.py`):

import socket

def start_ping_client():
host = '127.0.0.1'
port = 12346

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as client_socket:


client_socket.connect((host, port))
client_socket.sendall(b"Ping")
data = client_socket.recv(1024)
print(f"Received from server: {data.decode()}")

if __name__ == "__main__":
start_ping_client()

c. Write a Socket program for Chat applications.

Chat Server (`chat_server.py`):


import socket
import threading

def handle_client(client_socket, address):


while True:
message = client_socket.recv(1024)
if not message:
break
print(f"Received from {address}: {message.decode()}")
client_socket.sendall(message)

client_socket.close()

def start_chat_server():
host = '127.0.0.1'
port = 12347

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server_socket:


server_socket.bind((host, port))
server_socket.listen()

print(f"Chat server listening on {host}:{port}")

while True:
client_socket, address = server_socket.accept()
print(f"Accepted connection from {address}")
client_handler = threading.Thread(target=handle_client, args=(client_socket,
address))
client_handler.start()

if __name__ == "__main__":
start_chat_server()

Chat Client (`chat_client.py`):


import socket

def start_chat_client():
host = '127.0.0.1'
port = 12347

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as client_socket:


client_socket.connect((host, port))

while True:
message = input("Enter message to send to the server (or 'exit' to quit): ")
if message.lower() == 'exit':
break
client_socket.sendall(message.encode())

print("Chat client is exiting.")

if __name__ == "__main__":
start_chat_client()

d. Write a Socket program for DNS(Domain Name System)

DNS Server (`dns_server.py`):

import socket

def start_dns_server():
host = '127.0.0.1'
port = 53 # DNS standard port

with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as server_socket:


server_socket.bind((host, port))

print(f"DNS server listening on {host}:{port}")

while True:
data, client_address = server_socket.recvfrom(1024)
print(f"Received DNS query from {client_address}")
# Implement DNS resolution logic here
# Respond to the client with the appropriate DNS information

if __name__ == "__main__":
start_dns_server()
21. Planning Network-based Firewalls

Planning network-based firewalls involves strategically designing the implementation of


firewalls within a network to enhance security. Here's a concise overview:

1. Define Objectives: Clearly outline security goals and identify threats.

2. Assess Network Topology: Understand network structure and critical assets.

3. Segmentation: Isolate network segments based on security needs.

4. Firewall Placement: Decide where to position firewalls (perimeter, internal, host-based).

5. Select Technology: Choose the right firewall type (stateful, NGFW, proxy, UTM).

6. Security Policies: Develop comprehensive rules for traffic control.

7. Logging and Monitoring: Configure logs and implement monitoring for threat detection.

8. User Authentication: Implement user authentication and access controls.

9. Update and Patch Management: Regularly update firewall firmware and apply patches.

10. Incident Response: Develop a plan for responding to security incidents.

11. Testing and Evaluation: Conduct regular tests and evaluations, including penetration
testing.

12. Training and Awareness: Train personnel on firewall management and raise security
awareness.

13. Compliance: Ensure firewall configuration aligns with industry regulations.

14. Documentation: Maintain detailed documentation of configurations and policies.

15. Regular Review: Periodically review and update firewall configurations to adapt to
changes.

This planning ensures that firewalls are strategically positioned, configured, and maintained
to protect the network against various threats while meeting compliance standards.

You might also like