0% found this document useful (0 votes)
14 views

Computer - Networking - Saviour Final

computer networkring sem6 b terch cse

Uploaded by

pathocentre
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Computer - Networking - Saviour Final

computer networkring sem6 b terch cse

Uploaded by

pathocentre
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

Computer Networking lab

List of Experiment:

1. Write a program in c to implement Cyclic Redundancy Check for error


detection and modulo 2 binary division.

Sol->
#include <bits/stdc++.h>

using namespace std;

// Returns XOR of 'a' and 'b'


// (both of same length)
string xor1(string a, string b)
{

// Initialize result

string result = "";

int n = b.length();

// Traverse all bits, if bits are

// same, then XOR is 0, else 1

for (int i = 1; i < n; i++) {

if (a[i] == b[i])

result += "0";

else

result += "1";

}
return result;
}

// Performs Modulo-2 division


string mod2div(string dividend, string divisor)
{

// Number of bits to be XORed at a time.

int pick = divisor.length();

// Slicing the dividend to appropriate

// length for particular step

string tmp = dividend.substr(0, pick);

int n = dividend.length();

while (pick < n) {

if (tmp[0] == '1')

// Replace the dividend by the result

// of XOR and pull 1 bit down

tmp = xor1(divisor, tmp) + dividend[pick];

else

// If leftmost bit is '0'.

// If the leftmost bit of the dividend (or the


// part used in each step) is 0, the step cannot

// use the regular divisor; we need to use an

// all-0s divisor.

tmp = xor1(std::string(pick, '0'), tmp)

+ dividend[pick];

// Increment pick to move further

pick += 1;

// For the last n bits, we have to carry it out

// normally as increased value of pick will cause

// Index Out of Bounds.

if (tmp[0] == '1')

tmp = xor1(divisor, tmp);

else

tmp = xor1(std::string(pick, '0'), tmp);

return tmp;
}

// Function used at the sender side to encode


// data by appending remainder of modular division
// at the end of data.

void encodeData(string data, string key)


{
int l_key = key.length();

// Appends n-1 zeroes at end of data

string appended_data

= (data + std::string(l_key - 1, '0'));

string remainder = mod2div(appended_data, key);

// Append remainder in the original data

string codeword = data + remainder;

cout << "Remainder : " << remainder << "\n";

cout << "Encoded Data (Data + Remainder) :" << codeword

<< "\n";
}
// checking if the message received by receiver is correct
// or not. If the remainder is all 0 then it is correct,
// else wrong.

void receiver(string data, string key)


{

string currxor

= mod2div(data.substr(0, key.size()), key);

int curr = key.size();

while (curr != data.size()) {

if (currxor.size() != key.size()) {

currxor.push_back(data[curr++]);

else {
currxor = mod2div(currxor, key);

if (currxor.size() == key.size()) {

currxor = mod2div(currxor, key);

if (currxor.find('1') != string::npos) {

cout << "there is some error in data" << endl;

else {

cout << "correct message received" << endl;

}
}
// Driver code

int main()
{

string data = "1001101";

string key = "1011";

cout << "Sender side..." << endl;

encodeData(data, key);

cout << "\nReceiver side..." << endl;

receiver(data+mod2div(data+std::string(key.size() - 1, '0'),key), key);

return 0;
}
// This code is contributed by MuskanKalra1 , Mayank Sharma

Output:

Sender side...

Remainder : 101

Encoded Data (Data + Remainder) :1001101101

Receiver side...

correct message received

2. (a)Write a C program to compute the Hamming Distance between two

code-words (binary strings of equal length).

Sol->
#include <bits/stdc++.h>
using namespace std;

// function to calculate Hamming distance


int hammingDist(string str1, string str2)
{
int i = 0, count = 0;
while (str1[i] != '\0') {
if (str1[i] != str2[i])
count++;
i++;
}
return count;
}

// driver code
int main()
{
string str1 = "10110";
string str2 = "10101";
// function call
cout << "hamming dist is:"<<hammingDist(str1, str2);
return 0;
}

Input (a): X = [ 0 1 1 1 0], Y = [ 0 0 1 1 1 ]

Output(a): hamming dist is:2

(b) Write a C Program to compute the minimal Hamming Distance (d_min)

for a set of binary input strings (of same length).

Soln->

#include <bits/stdc++.h>
using namespace std;

// Function to calculate the Hamming distance between two binary strings


int hammingDistance(const string &str1, const string &str2) {
int distance = 0;
for (size_t i = 0; i < str1.size(); ++i) {
if (str1[i] != str2[i]) {
++distance;
}
}
return distance;
}

int main() {
int n;
cin>>n;
string mainString;
cout << "Enter the main binary string: ";
cin >> mainString;
vector<string> binaryStrings(n);
cout << "Enter 4 binary strings of equal length:" << endl;
for (int i = 0; i < n; ++i) {
cin >> binaryStrings[i];
}
int minHammingDistance = INT_MAX;

// Calculate Hamming distance for each pair of binary strings


for (const auto &binaryString : binaryStrings) {
int distance = hammingDistance(mainString, binaryString);
minHammingDistance = min(minHammingDistance, distance);
}

cout << "The minimum Hamming distance among the 4 binary strings is: " <<
minHammingDistance << endl;

return 0;
}

Output(b):

4
Enter the main binary string: 10101
Enter 4 binary strings of equal length:
11101
11010
01011
10101
The minimum Hamming distance among the 4 binary strings is: 0
Note: Take appropriate user inputs, intermediate metrics; and show the output.

3. Write a program in c to implement row and column parity of a 2D matrix.

Soln->

#include <iostream>
#include <vector>
#include <string>
#include <sstream>

using namespace std;

// Function to print the matrix with parity bits


void printMatrixWithParity(const vector<vector<int>>& matrix) {
int rows = matrix.size();
int cols = matrix[0].size();
// Print the original matrix with row parity
for (int i = 0; i < rows - 1; ++i) {
for (int j = 0; j < cols - 1; ++j) {
cout << matrix[i][j] << " ";
}
// Print row parity bit
cout << "| " << matrix[i][cols - 1] << endl;
}

// Print column parity bits


for (int j = 0; j < cols - 1; ++j) {
cout << "--";
}
cout << "---" << endl;

for (int j = 0; j < cols - 1; ++j) {


cout << matrix[rows - 1][j] << " ";
}
cout << endl;
}

int main() {
int rows, cols;
cout << "Enter the number of rows: ";
cin >> rows;
cout << "Enter the number of columns: ";
cin >> cols;

cin.ignore(); // To ignore the newline character after the number input

// Create a matrix with an extra row and column for parity bits
vector<vector<int>> matrix(rows + 1, vector<int>(cols + 1, 0));

// Input the matrix values as a string


cout << "Enter the matrix values (0 or 1) as a single string (e.g., 101010110):" << endl;
string input;
getline(cin, input);

if (input.length() != rows * cols) {


cerr << "Input string length does not match the matrix size." << endl;
return 1;
}

// Populate the matrix from the string input


int index = 0;
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
matrix[i][j] = input[index++] - '0'; // Convert char to int
}
}

// Calculate row parity bits


for (int i = 0; i < rows; ++i) {
int parity = 0;
for (int j = 0; j < cols; ++j) {
parity ^= matrix[i][j]; // XOR operation
}
matrix[i][cols] = parity;
}

// Calculate column parity bits


for (int j = 0; j < cols; ++j) {
int parity = 0;
for (int i = 0; i < rows; ++i) {
parity ^= matrix[i][j]; // XOR operation
}
matrix[rows][j] = parity;
}

// Print the matrix with parity bits


cout << "Matrix with parity bits:" << endl;
printMatrixWithParity(matrix);

return 0;
}

Output:

Enter the number of rows: 3


Enter the number of columns: 8
Enter the matrix values (0 or 1) as a single string (e.g., 101010110):
110110011001111010110011
Matrix with parity bits:
11011001|1
10011110|1
10110011|1
-------------------
11110100
4. Write a program in c for error detection using checksum (frame length =
3).

Code:

WITH USER INPUT AND FRAME SIZE (If both sender and receiver given):

#include <bits/stdc++.h>

using namespace std;

string Ones_complement(string data)

for (int i = 0; i < data.length(); i++) {

if (data[i] == '0')

data[i] = '1';

else

data[i] = '0';

return data;

string checkSum(string data, int block_size)

int n = data.length();

if (n % block_size != 0) {

int pad_size = block_size - (n % block_size);

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

data = '0' + data;

string result = "";

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

result += data[i];

}
for (int i = block_size; i < n; i += block_size) {

string next_block = "";

for (int j = i; j < i + block_size; j++) {

next_block += data[j];

string additions = "";

int sum = 0, carry = 0;

for (int k = block_size - 1; k >= 0; k--) {

sum += (next_block[k] - '0')

+ (result[k] - '0');

carry = sum / 2;

if (sum == 0) {

additions = '0' + additions;

sum = carry;

else if (sum == 1) {

additions = '1' + additions;

sum = carry;

else if (sum == 2) {

additions = '0' + additions;

sum = carry;

else {

additions = '1' + additions;

sum = carry;

string final = "";

if (carry == 1) {

for (int l = additions.length() - 1; l >= 0;


l--) {

if (carry == 0) {

final = additions[l] + final;

else if (((additions[l] - '0') + carry) % 2

== 0) {

final = "0" + final;

carry = 1;

else {

final = "1" + final;

carry = 0;

result = final;

else {

result = additions;

return Ones_complement(result);

bool checker(string sent_message,

string rec_message,

int block_size)

string sender_checksum

= checkSum(sent_message, block_size);

string receiver_checksum = checkSum(

rec_message + sender_checksum, block_size);

if (count(receiver_checksum.begin(),
receiver_checksum.end(), '0')

== block_size) {

return true;

else {

return false;

int main()

string sent_message

= "101111011110";

string recv_message

= "101111011110";

int block_size = 3;

if (checker(sent_message,

recv_message,

block_size)) {

cout << "No Error";

else {

cout << "Error";

return 0;

Output:

No Error
5. (a) Let us consider that we need to develop a routing technique in IPv4

standard. As a part of that Source and Destination IP addresses are to be

identified from the received IP datagram. We need to develop such kind of

system where user input will be dotted decimal value of IP address in classful
addressing scheme.

Code:

#include <iostream>

#include <sstream>

#include <vector>

using namespace std;

// Function to split a string by a delimiter

vector<string> split(const string& str, char delimiter) {

vector<string> tokens;

string token;

istringstream tokenStream(str);

while (getline(tokenStream, token, delimiter)) {

tokens.push_back(token);

return tokens;

// Function to convert dotted decimal IP to 32-bit unsigned integer

uint32_t ipToUint(const string& ip) {

vector<string> octets = split(ip, '.');

uint32_t result = 0;
for (const string& octet : octets) {

result = (result << 8) + stoi(octet);

return result;

// Function to convert 32-bit unsigned integer to dotted decimal IP

string uintToIp(uint32_t ip) {

return to_string((ip >> 24) & 0xFF) + "." +

to_string((ip >> 16) & 0xFF) + "." +

to_string((ip >> 8) & 0xFF) + "." +

to_string(ip & 0xFF);

int main() {

string sourceIpStr, destinationIpStr;

cout << "Enter the source IP address in dotted decimal format: ";

cin >> sourceIpStr;

cout << "Enter the destination IP address in dotted decimal format: ";

cin >> destinationIpStr;

// Convert IP addresses to 32-bit unsigned integers

uint32_t sourceIp = ipToUint(sourceIpStr);

uint32_t destinationIp = ipToUint(destinationIpStr);

// Display the results

cout << "Source IP Address: " << uintToIp(sourceIp) << endl;

cout << "Destination IP Address: " << uintToIp(destinationIp) << endl;

return 0;

}
Output:

Enter the source IP address in dotted decimal format: 192.168.1.1

Enter the destination IP address in dotted decimal format: 10.0.0.1

Source IP Address: 192.168.1.1

Destination IP Address: 10.0.0.1

(b) Write a C program to identify the class of the IP address along with the

network ID of the given IP address.

Example: Input: 120.90.10.90, Output: Class: A, etc.

Code:

#include <iostream>

#include <string>

#include <vector>

#include <sstream>

using namespace std;

// Function to split a string by a delimiter

vector<string> split(const string& str, char delimiter) {

vector<string> tokens;

string token;

istringstream tokenStream(str);
while (getline(tokenStream, token, delimiter)) {

tokens.push_back(token);

return tokens;

// Function to determine the class of the IP address and the network ID

void identifyClassAndNetworkID(const string& ip) {

vector<string> octets = split(ip, '.');

int firstOctet = stoi(octets[0]);

string ipClass;

string networkID;

if (firstOctet >= 1 && firstOctet <= 126) {

ipClass = "A";

networkID = octets[0];

} else if (firstOctet >= 128 && firstOctet <= 191) {

ipClass = "B";

networkID = octets[0] + "." + octets[1];

} else if (firstOctet >= 192 && firstOctet <= 223) {

ipClass = "C";

networkID = octets[0] + "." + octets[1] + "." + octets[2];

} else if (firstOctet >= 224 && firstOctet <= 239) {

ipClass = "D (Multicast)";

} else if (firstOctet >= 240 && firstOctet <= 255) {

ipClass = "E (Reserved)";

} else {

ipClass = "Invalid IP Address";

}
cout << "Class: " << ipClass << endl;

if (!networkID.empty()) {

cout << "Network ID: " << networkID << endl;

int main() {

string ipAddress;

cout << "Enter the IP address in dotted decimal format: ";

cin >> ipAddress;

identifyClassAndNetworkID(ipAddress);

return 0;

Output:

Enter the IP address in dotted decimal format: 120.90.10.90

Class: A

Network ID: 120

(c) Convert the dotted decimal into 32 bits IP address and check the class of
the IP

address using the binary blocks (1 byte or 8 bits length each).

Code:

#include <iostream>

#include <sstream>

#include <bitset>
#include <vector>

using namespace std;

// Function to split a string by a delimiter

vector<string> split(const string& str, char delimiter) {

vector<string> tokens;

string token;

istringstream tokenStream(str);

while (getline(tokenStream, token, delimiter)) {

tokens.push_back(token);

return tokens;

// Function to convert dotted decimal IP to 32-bit unsigned integer

uint32_t ipToUint(const string& ip) {

vector<string> octets = split(ip, '.');

uint32_t result = 0;

for (const string& octet : octets) {

result = (result << 8) + stoi(octet);

return result;

// Function to determine the class of the IP address based on the first byte

char getClass(uint8_t firstByte) {

if (firstByte >= 1 && firstByte <= 126) {

return 'A';

} else if (firstByte >= 128 && firstByte <= 191) {


return 'B';

} else if (firstByte >= 192 && firstByte <= 223) {

return 'C';

} else if (firstByte >= 224 && firstByte <= 239) {

return 'D';

} else if (firstByte >= 240 && firstByte <= 255) {

return 'E';

} else {

return 'I'; // Invalid

int main() {

string ipAddress;

cout << "Enter the IP address in dotted decimal format: ";

cin >> ipAddress;

// Convert IP address to 32-bit unsigned integer

uint32_t ipAsUint = ipToUint(ipAddress);

// Convert 32-bit unsigned integer to binary string

bitset<32> ipAsBinary(ipAsUint);

// Extract the first byte to determine the class

uint8_t firstByte = (ipAsUint >> 24) & 0xFF;

char ipClass = getClass(firstByte);

// Display the results

cout << "IP Address in 32-bit binary format: " << ipAsBinary << endl;

if (ipClass != 'I') {

cout << "Class: " << ipClass << endl;


} else {

cout << "Invalid IP Address" << endl;

return 0;

Output:

Enter the IP address in dotted decimal format: 120.90.10.90

IP Address in 32-bit binary format: 01111000010110100000101001011010

Class: A

(d) Let consider a classless IPv4 IP datagram.

i) Write a C program to identify the first and last IP addresses of the network.

Code:

#include <iostream>

#include <sstream>

#include <vector>

#include <bitset>

#include <cmath>

using namespace std;

// Function to split a string by a delimiter


vector<string> split(const string& str, char delimiter) {

vector<string> tokens;

string token;

istringstream tokenStream(str);

while (getline(tokenStream, token, delimiter)) {

tokens.push_back(token);

return tokens;

// Function to convert dotted decimal IP to 32-bit unsigned integer

uint32_t ipToUint(const string& ip) {

vector<string> octets = split(ip, '.');

uint32_t result = 0;

for (const string& octet : octets) {

result = (result << 8) + stoi(octet);

return result;

// Function to convert 32-bit unsigned integer to dotted decimal IP

string uintToIp(uint32_t ip) {

return to_string((ip >> 24) & 0xFF) + "." +

to_string((ip >> 16) & 0xFF) + "." +

to_string((ip >> 8) & 0xFF) + "." +

to_string(ip & 0xFF);

int main() {

string input;

cout << "Enter the IP address in CIDR notation (e.g., 205.16.37.39/28): ";
cin >> input;

// Split input into IP address and CIDR prefix

vector<string> ipAndCidr = split(input, '/');

string ipAddress = ipAndCidr[0];

int cidr = stoi(ipAndCidr[1]);

// Convert IP address to 32-bit unsigned integer

uint32_t ipAsUint = ipToUint(ipAddress);

// Calculate subnet mask

uint32_t mask = (0xFFFFFFFF << (32 - cidr)) & 0xFFFFFFFF;

// Calculate network address

uint32_t networkAddress = ipAsUint & mask;

// Calculate broadcast address

uint32_t broadcastAddress = networkAddress | ~mask;

// Calculate first and last IP addresses

uint32_t firstIpAddress = networkAddress + 1;

uint32_t lastIpAddress = broadcastAddress - 1;

// Display results

cout << "Network Address: " << uintToIp(networkAddress) << endl;

cout << "First IP Address: " << uintToIp(firstIpAddress) << endl;

cout << "Last IP Address: " << uintToIp(lastIpAddress) << endl;

cout << "Broadcast Address: " << uintToIp(broadcastAddress) << endl;

return 0;

}
Output:

Enter the IP address in CIDR notation (e.g., 205.16.37.39/28): 205.16.37.39/28

Network Address: 205.16.37.32

First IP Address: 205.16.37.33

Last IP Address: 205.16.37.46

Broadcast Address: 205.16.37.47

ii) Write a C program to generate all the IP addresses of the network.

Example: Input 205.16.37.39/28

Code:

#include <iostream>

#include <sstream>

#include <vector>

#include <bitset>

#include <cmath>

using namespace std;

// Function to split a string by a delimiter

vector<string> split(const string& str, char delimiter) {

vector<string> tokens;

string token;

istringstream tokenStream(str);
while (getline(tokenStream, token, delimiter)) {

tokens.push_back(token);

return tokens;

// Function to convert dotted decimal IP to 32-bit unsigned integer

uint32_t ipToUint(const string& ip) {

vector<string> octets = split(ip, '.');

uint32_t result = 0;

for (const string& octet : octets) {

result = (result << 8) + stoi(octet);

return result;

// Function to convert 32-bit unsigned integer to dotted decimal IP

string uintToIp(uint32_t ip) {

return to_string((ip >> 24) & 0xFF) + "." +

to_string((ip >> 16) & 0xFF) + "." +

to_string((ip >> 8) & 0xFF) + "." +

to_string(ip & 0xFF);

int main() {

string input;

cout << "Enter the IP address in CIDR notation (e.g., 205.16.37.39/28): ";

cin >> input;

// Split input into IP address and CIDR prefix

vector<string> ipAndCidr = split(input, '/');


string ipAddress = ipAndCidr[0];

int cidr = stoi(ipAndCidr[1]);

// Convert IP address to 32-bit unsigned integer

uint32_t ipAsUint = ipToUint(ipAddress);

// Calculate subnet mask

uint32_t mask = (0xFFFFFFFF << (32 - cidr)) & 0xFFFFFFFF;

// Calculate network address

uint32_t networkAddress = ipAsUint & mask;

// Calculate broadcast address

uint32_t broadcastAddress = networkAddress | ~mask;

// Calculate first and last IP addresses

uint32_t firstIpAddress = networkAddress + 1;

uint32_t lastIpAddress = broadcastAddress - 1;

// Display all IP addresses in the network

cout << "All IP addresses in the network: " << endl;

for (uint32_t ip = firstIpAddress; ip <= lastIpAddress; ++ip) {

cout << uintToIp(ip) << endl;

return 0;

Output:

Enter the IP address in CIDR notation (e.g., 205.16.37.39/28): 205.16.37.39/28


All IP addresses in the network:

205.16.37.33

205.16.37.34

205.16.37.35

205.16.37.36

205.16.37.37

205.16.37.38

205.16.37.39

205.16.37.40

205.16.37.41

205.16.37.42

205.16.37.43

205.16.37.44

205.16.37.45

205.16.37.46

(e) Let consider that if the user mentions the possible number of hosts
required

in the network. Write a C program to check whether this IP class is suitable or


not.

Let say, required number of host (n) = 45. Justify your answer!

Code:

#include <iostream>

using namespace std;

bool isClassASuitable(int hosts) {

return hosts <= (1 << 24) - 2;

}
bool isClassBSuitable(int hosts) {

return hosts <= (1 << 16) - 2;

bool isClassCSuitable(int hosts) {

return hosts <= (1 << 8) - 2;

int main() {

long long requiredHosts;

cout<<"enter the no of reqiured hosts:";

cin>>requiredHosts;

cout << "Required number of hosts: " << requiredHosts << endl;

if (isClassASuitable(requiredHosts)) {

cout << "Class A IP address is suitable." << endl;

} else {

cout << "Class A IP address is not suitable." << endl;

if (isClassBSuitable(requiredHosts)) {

cout << "Class B IP address is suitable." << endl;

} else {

cout << "Class B IP address is not suitable." << endl;

if (isClassCSuitable(requiredHosts)) {

cout << "Class C IP address is suitable." << endl;

} else {
cout << "Class C IP address is not suitable." << endl;

return 0;

Output:

enter the no of reqiured hosts:45

Required number of hosts: 45

Class A IP address is suitable.

Class B IP address is suitable.

Class C IP address is suitable.

You might also like