Lab Fat: Cse1004 - Network and Communication

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

CSE1004 – NETWORK AND COMMUNICATION

(Embedded Lab)

LAB FAT

(B.Tech. 2ND YEAR )


WINTER SEMESTER 2021-2022

Name CHEBROLU SAI PRASANNA ABHINAV

Reg. No. 20BCE2425

Slot L53 + L54

Faculty Name: MANIKANDAN K


CHEBROLU SAI PRASANNA ABHINAV – 20BCE2425

1B (i) CRC Cycle Redundancy Check

Aim : To implement a program for the Cyclic Redundancy Check (CRC) Mechanism and display
the output for a given input.

Algorithm :

1. Start.
2. CRC uses Modulo 2 division method.
3. CRC uses Generator polynomial (Divisor)/ which receiver and sender both knows about it.
4. Generator polynomial can also be treated as bit set of bits which divides data bits.
5. Sender Side(Generation of Encoded Data from sender side ):
a) The binary data is first augmented by adding k-1 zeros in the end of the data .
b) Use modulo-2 binary division to divide binary data by the key and store remainder of
division.
c) Append the remainder at the end of the data to form the encoded data and send the
same.
6. Receiver Side :Perform modulo-2 division again and if remainder is 0, then there are no errors.
7. End.

CRC or Cyclic Redundancy Check is a method of detecting accidental changes/errors in the


communication channel. CRC uses Generator Polynomial which is available on both sender and receiver
side. An example generator polynomial is of the form like x3 + x + 1. This generator polynomial
represents key 1011. Another example is x2 + 1 that represents key 101.

2 Division: The process of modulo-2 binary division is the same as the familiar division process we use
for decimal numbers. Just that instead of subtraction, we use XOR here. In each step, a copy of the
divisor (or data) is XORed with the k bits of the dividend (or key). The result of the XOR operation
(remainder) is (n-1) bits, which is used for the next step after 1 extra bit is pulled down to make it n bits
long. When there are no bits left to pull down, we have a result. The (n-1)-bit remainder which is
appended at the sender side.

Sender
Sender Side (Generation of Encoded Data from Data and Generator Polynomial (or Key)):

1. The binary data is first augmented by adding k-1 zeros in the end of the data.
2. Use modulo-2 binary division to divide binary data by the key and store remainder of division.
3. Append the remainder at the end of the data to form the encoded data and send the same

Input :

#include<iostream>
using namespace std;
int main()
{
string msg, crc, encoded="";
cout<<"Enter the Dataword = ";
getline(cin,msg);
cout<<"Enter the CRC divisor = ";
getline(cin,crc);
int m=msg.length(),
n=crc.length();
encoded+=msg;

Network and Communication : Lab FAT : 28-04-2022 1


CHEBROLU SAI PRASANNA ABHINAV – 20BCE2425

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


encoded+="0";
for(int i=0; i<=encoded.length()-n; ){
for(int j=0; j<n; j++)
encoded[i+j]=encoded[i+j]==crc[j]? '0':'1';
for(;i<encoded.length() && encoded[i]!='1'; i++);
}
cout<<"Remainder is : "<<encoded.substr(encoded.length()-n+1)<<endl;
cout<<"The Code word is : "<<msg+encoded.substr(encoded.length()-n+1);
return 0;
}

Output :

Reciever
Receiver Side (Check if there are errors introduced in transmission)
1. Perform modulo-2 division again and if the remainder is 0, then there are no errors.
2. In this article we will focus only on finding the remainder i.e. check word and the code word.
Modulo

Input :
#include<iostream>
using namespace std;
int main()
{
string crc, encoded;
cout<<"Enter the Codeword = ";
getline(cin, encoded);
cout<<"Enter the CRC Divisor = ";
getline(cin, crc);
for(int i=0; i<=encoded.length()-crc.length();){
for(int j=0; j<crc.length(); j++)
encoded[i+j]=encoded[i+j]==crc[j]? '0':'1';
for(; i<encoded.length() && encoded[i]!='1';i++);
}
for(char i: encoded.substr(encoded.length()-crc.length()))
if(i!='0'){
cout<<"Error in communication";
return 0;
}
cout<<"No Error"<<endl;
return 0;

Network and Communication : Lab FAT : 28-04-2022 2


CHEBROLU SAI PRASANNA ABHINAV – 20BCE2425

Output :

Using user defined functions :

Input :

#include<iostream>
#include<string.h>
using namespace std;
class CRC {
string input,divisor,divident,result;
int len_divident, len_gen, len_inp;
public:
string fun_xor(string a,string b)
{
string result="";
if(a[0]=='0')
return a.substr(1);
else
{
for(int i=0;i<len_gen;i++)
{
result=result+(a[i]==b[i]?'0':'1');
}
return result.substr(1);
}
}
void modulo_div()
{
string temp_div=divisor;
string temp_divident=divident.substr(0,len_gen);
int j=len_gen;
while(j<len_divident)
{
temp_divident=fun_xor(temp_divident,temp_div);
temp_divident=temp_divident+divident[j];
j++;
}
result=input+fun_xor(temp_divident, temp_div);
}
void getdata()
{
cout<<"Sender side\n";

Network and Communication : Lab FAT : 28-04-2022 3


CHEBROLU SAI PRASANNA ABHINAV – 20BCE2425

cout<<"Enter the Dataword = ";


cin>>input;
cout<<"Enter the CRC divisor = ";
cin>>divisor;
len_gen=divisor.length();
len_inp=input.length();
divident=input;
int r=len_gen-1;
for(int i=0;i<r;i++)
{
divident=divident+'0';
}
len_divident=divident.length();
modulo_div();
}
void sender_side()
{
cout<<"Dataword : "<<input<<"\n";
cout<<"Divisor : "<<divisor<<"\n";
cout<<"Codeword : "<<result<<"\n";
}
void receiver_side()
{
cout<<"\nReciver side\n";
string data_rec;
cout<<"Enter the Codeword = ";
cin>>data_rec;

string temp_div=divisor;
string temp_divident=data_rec.substr(0,len_gen);
int j=len_gen;
while(j<data_rec.length())
{
temp_divident=fun_xor(temp_divident,temp_div);
temp_divident=temp_divident+data_rec[j];
j++;
}
string error=fun_xor(temp_divident, temp_div);
cout<<"Remainder Syndrome is : "<<error<<"\n";
bool flag=0;
for(int i=0;i<len_gen-1;i++)
{
if(error[i]=='1')
{
flag=1;
break;
}
}
if(flag==0)
cout<<"No Error";
else
cout<<"Error in communication";
}

Network and Communication : Lab FAT : 28-04-2022 4


CHEBROLU SAI PRASANNA ABHINAV – 20BCE2425

};
int main() {
CRC crc;
crc.getdata();
crc.sender_side();
crc.receiver_side();
return 0;
}

Output :

Contd…

Network and Communication : Lab FAT : 28-04-2022 5


CHEBROLU SAI PRASANNA ABHINAV – 20BCE2425

1B(ii) Check Sum Error Detection

Aim : To implement a program for Checksum Mechanism and display the output for a given input.

Algorithm :
1. Start
2. In checksum error detection scheme, the data is divided into k segments each of m bits.
3. In the sender’s end the segments are added using 1’s complement arithmetic to get the sum.
The sum is complemented to get the checksum.
4. The checksum segment is sent along with the data segments.
5. At the receiver’s end, all received segments are added using 1’s complement arithmetic to get
the sum. The sum is complemented.
6. If the result is zero, the received data is accepted; otherwise discarded.
7. End.

Checksum is the error detection method used by upper layer protocols and is considered to be more
reliable than LRC, VRC and CRC. This method makes the use of Checksum Generator on Sender side and
Checksum Checker on Receiver side.

Sender
At the Sender side, the data is divided into equal subunits of n bit length by the checksum generator. This
bit is generally of 16-bit length. These subunits are then added together using one’s complement
method. This sum is of n bits. The resultant bit is then complemented. This complemented sum which is
called checksum is appended to the end of original data unit and is then transmitted to Receiver.

Reciever side

The Receiver after receiving data + checksum passes it to checksum checker. Checksum checker divides
this data unit into various subunits of equal length and adds all these subunits. These subunits also
contain checksum as one of the subunits. The resultant bit is then complemented. If the complemented
result is zero, it means the data is error-free. If the result is non-zero it means the data contains an error
and Receiver rejects it.

Input :

#include<stdio.h>
#include<math.h>
int sender(int b[10],int k)
{
int checksum,sum=0,i;
printf("\nSender Side\n");
for(i=0;i<k;i++)
sum+=b[i];
printf("Sender Side's Sum : %d",sum);
checksum=~sum;
printf("\nSender Side's Checksum:%d",checksum);
return checksum;
}
int receiver(int c[10],int k,int scheck)
{
int checksum,sum=0,i;
printf("\n\nReceiver Side\n");
for(i=0;i<k;i++)

Network and Communication : Lab FAT : 28-04-2022 6


CHEBROLU SAI PRASANNA ABHINAV – 20BCE2425

sum+=c[i];
printf("Receiver Side's Sum : %d",sum);
sum=sum+scheck;
checksum=~sum;
printf("\nReceiver Side's Checksum : %d",checksum);
return checksum;
}
int main()
{
int a[10],i,size,scheck,rcheck;
printf("Enter the size of the string : ");
scanf("%d",&size);
printf("Enter the message : ");
for(i=0;i<size;i++)
scanf("%d",&a[i]);
scheck=sender(a,size);
rcheck=receiver(a,size,scheck);
if(rcheck==0)
printf("\n\nNO ERROR\n\n");
else
printf("\n\nERROR DETECTED");

Output :

Network and Communication : Lab FAT : 28-04-2022 7


CHEBROLU SAI PRASANNA ABHINAV – 20BCE2425

Question Paper
1. Implement the following Flow Control Protocol
a) Stop and Wait ARQ
b) Go back ‘n’ ARQ
c) Selective Repeat ARQ

1A) Stop and Wait ARQ Protocol

Aim : To implement a program for Stop and Wait ARQ and display the output for a given input.

Algorithm :
1. Start the program.
2. Generate a random timer that gives the total number of frames to be transmitted.
3. Transmit the first frame.
4. Receive the acknowledgement for the first frame.
5. Transmit the next frame.
6. Find the remaining frames to be sent.
7. If an acknowledgement is not received for a particular frame retransmit that frame
8. alone again.
9. Repeat the steps 5 to 7 till the number of remaining frames to be send becomes zero.
10. Stop the program.

Input :

#include<iostream>
#include <time.h>
#include <cstdlib>
#include<ctime>
#include <unistd.h>
using namespace std;
class timer {
private:
unsigned long begTime;
public:
void start() {
begTime = clock();
}
unsigned long elapsedTime() {
return ((unsigned long) clock() - begTime) / CLOCKS_PER_SEC;
}
bool isTimeout(unsigned long seconds) {
return seconds >= elapsedTime();
}
};
int main()
{
int frames[] = {1,2,3,4,5,6,7,8,9,10};
unsigned long seconds = 5;
srand(time(NULL));
timer t;
cout<<"Sender has to send frames : ";

Network and Communication : Lab FAT : 28-04-2022 8


CHEBROLU SAI PRASANNA ABHINAV – 20BCE2425

for(int i=0;i<10;i++)
cout<<frames[i]<<" ";
cout<<endl;
int count = 0;
bool delay = false;
cout<<endl<<"Sender\t\t\t\t\tReceiver"<<endl;
do
{
bool timeout = false;
cout<<"Sending Frame : "<<frames[count];
cout.flush();
cout<<"\t\t";
t.start();
if(rand()%2)
{
int to = 24600 + rand()%(64000 - 24600) + 1;
for(int i=0;i<64000;i++)
for(int j=0;j<to;j++) {}
}
if(t.elapsedTime() <= seconds)
{
cout<<"Received Frame : "<<frames[count]<<" ";
if(delay)
{
cout<<"Duplicate";
delay = false;
}
cout<<endl;
count++;
}
else
{
cout<<"---"<<endl;
cout<<"Timeout"<<endl;
timeout = true;
}
t.start();
if(rand()%2 || !timeout)
{
int to = 24600 + rand()%(64000 - 24600) + 1;
for(int i=0;i<64000;i++)
for(int j=0;j<to;j++) {}
if(t.elapsedTime() > seconds )
{
cout<<"Delayed Ack"<<endl;
count--;
delay = true;
}
else if(!timeout)
cout<<"Acknowledgement : "<<frames[count]-1<<endl;
}
}while(count!=10);
return 0;

Network and Communication : Lab FAT : 28-04-2022 9


CHEBROLU SAI PRASANNA ABHINAV – 20BCE2425

Output :

1B) Go-Back N ARQ Alorithm

Aim : To implement a program for Go-Back N ARQ and display the output for a given input.

Algorithm :
1. Start the program.
2. Generate a random that gives the total number of frames to be transmitted.
3. Set the size of the window
4. Generate a random number less than or equal to the size of the current window and
identify the number of frames to be transmitted at a given time.
5. Transmit the frames and receive the acknowledgement for the frames sent.
6. Find the remaining frames to be sent.
7. Find the current window size.
8. If an acknowledgement is not received for a particular frame retransmit the frames from
that frame again.
9. Repeat the steps 4 to 8 till the number of remaining frames to be send becomes zero.

Network and Communication : Lab FAT : 28-04-2022 10


CHEBROLU SAI PRASANNA ABHINAV – 20BCE2425

10. Stop the program.

Input :

#include<iostream>
#include<ctime>
#include<cstdlib>
using namespace std;
int main()
{
int nf,N;
int no_tr=0;
srand(time(NULL));
cout<<"Enter the number of frames : ";cin>>nf;
cout<<"Enter the Window Size : ";
cin>>N;
int i=1;
while(i<=nf)
{
int x=0;
for(int j=i;j<i+N && j<=nf;j++)
{
cout<<"Sent Frame "<<j<<endl;
no_tr++;
}
for(int j=i;j<i+N && j<=nf;j++)
{
int flag = rand()%2;
if(!flag)
{
cout<<"Acknowledgment for Frame "<<j<<endl;
x++;
}
else
{ cout<<"Frame "<<j<<" Not Received"<<endl;
cout<<"Retransmitting Window"<<endl;
break;
}
}
cout<<endl;
i+=x;
}
cout<<"Total number of transmissions : "<<no_tr<<endl;
return 0;
}

Output :

Contd…

Network and Communication : Lab FAT : 28-04-2022 11


CHEBROLU SAI PRASANNA ABHINAV – 20BCE2425

1C) Selective Repeat ARQ Alorithm

Aim : To implement a program for Selective Repeat ARQ and display the output for a given input.

Algorithm :
1. Start the program.
2. Generate a random that gives the total number of frames to be transmitted.
3. Set the size of the window.
4. Generate a random number less than or equal to the size of the current window and
identify the number of frames to be transmitted at a given time.
5. Transmit the frames and receive the acknowledgement for the frames sent.
6. Find the remaining frames to be sent.
7. Find the current window size.
8. If an acknowledgement is not received for a particular frame retransmit that frame alone
again.
9. Repeat the steps 4 to 8 till the number of remaining frames to be send becomes zero.
10. Stop the program.

Contd…

Network and Communication : Lab FAT : 28-04-2022 12


CHEBROLU SAI PRASANNA ABHINAV – 20BCE2425

Input :

#include<stdio.h>
#include<stdlib.h>
#include<stdlib.h>
#define clrscr(); system("cls");
int main()
{
int number_of_frames, window_size;
int number_of_transmissions = 0;
printf("Enter the number of frames to be transmitted: ");
scanf("%d", &number_of_frames);
printf("Enter the window size: ");
scanf("%d", &window_size);
int i=1;
srand(time(NULL));
while(i<=number_of_frames) {
int x = 0;
for(int j=i; j<i+window_size && j<=number_of_frames; j++) {
printf("Sent Frame: %d\n", j);
number_of_transmissions++;
}
for(int j=i; j<i+window_size && j<=number_of_frames; j++) {
int flag = rand() % 2;
int flag1 = 1;
if(!flag) {
printf("Acknowledgment of frame : %d\n", j);
x++;
}
else {
while(flag1) {
printf("Negative Acknowledgment of frame: %d\n", j);
printf("Frame %d retransmitted", j);
number_of_transmissions++;
flag1 = rand() % 2;
}
x++;
}
}
printf("\n");
i+=x;
}
printf("Total number of transmissions: %d",
number_of_transmissions);
}

Output :

Contd…

Network and Communication : Lab FAT : 28-04-2022 13


CHEBROLU SAI PRASANNA ABHINAV – 20BCE2425

Question Paper
1. Dotted Decimal IP address format into Binary format
2. Binary format to Dotted decimal IP address format
3. Find the First address, Last address and Number of addresses from given IP address and Mask
4. Construct Various Subnet for an organization
5. Implement following Routing Protocol
a. Distance Vector Routing
b. Link State Routing

1) Dotted Decimal IP address format into Binary format

Aim : To implement a program for Dotted Decimal IP Address and display the output for a given
input.

Algorithm :

1. Ask user to enter choice i.e binary to decimal or vide versa


2. User enter choice
3. From Binary to Decimal
a. User inputs IP as string
b. String is split
c. Stored as integer array
d. convert function runs int dec = 0, i = 0, rem;
i. while (n != 0) {
ii. rem = n % 10;
iii. n /= 10;
iv. dec += rem * pow(2, i);
v. ++i;
vi. }
4. From Decimal to Binary

Network and Communication : Lab FAT : 28-04-2022 14


CHEBROLU SAI PRASANNA ABHINAV – 20BCE2425

a. User inputs string


b. String split and stored in integer array
c. (num%2==0) : either one or two
d. N=n/2
e. 4 times runs code and stored in backwards order
f. Output shown

Input : IP address in Decimals

Code :

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int convert_binary(int a, int b, int c, int d);
int * convert_binary1(int a);
main() {
int i, j;
int ip[4];
int binary[32];
int * bin;
char * piece;
char input[20];
printf("\nEnter ip address:");
scanf("%s", input);
piece = strtok(input, ".");
i = 0;
do {
ip[i++] = atoi(piece);
piece = strtok(NULL, ".");
} while (piece && i < 4);
for (j = 0; j < 4; j++) {
bin = convert_binary1(ip[j]);
for (i = 0; i < 8; i++) {
binary[j * 8 + i] = bin[i];
}
}
for (i = 0; i < 32; i++) {
if (i > 0 && (i) % 8 == 0) printf(".");
printf("%d", binary[i]);
}
printf("\n");
}
int * convert_binary1(int a) {
int i, j, k, l;
int * num = (int * ) malloc(sizeof(int) * 8);
for (i = 0; i <= 7; i++) {
num[7 - i] = a % 2;
a = a / 2;
}
return num;
}
int convert_binary(int a, int b, int c, int d) {

Network and Communication : Lab FAT : 28-04-2022 15


CHEBROLU SAI PRASANNA ABHINAV – 20BCE2425

int i, j, k, l;
int num[10];
for (i = 0; i <= 7; i++) {
num[i] = a % 2;
a = a / 2;
}
for (i = 7; i >= 0; i--) {
printf("%d", num[i]);
}
printf(".");
for (j = 0; j <= 7; j++) {
num[j] = b % 2;
b = b / 2;
}
for (j = 7; j >= 0; j--) {
printf("%d", num[j]);
}
printf(".");
for (k = 0; k <= 7; k++) {
num[k] = c % 2;
c = c / 2;
}
for (k = 7; k >= 0; k--) {
printf("%d", num[k]);
}
printf(".");
for (l = 0; l <= 7; l++) {
num[l] = d % 2;
d = d / 2;
}
for (l = 7; l >= 0; l--) {
printf("%d", num[l]);
}
}

Output :

2) Binary format to Dotted Decimal IP address format

Network and Communication : Lab FAT : 28-04-2022 16


CHEBROLU SAI PRASANNA ABHINAV – 20BCE2425

Aim : To implement a program for Binary format to dotted decimal IP address format and display
the output for a given input.

Algorithm :
1. Ask user to enter choice i.e binary to decimal or vide versa
2. User enter choice
3. From Binary to Decimal
a. User inputs IP as string
b. String is split
c. Stored as integer array
d. convert function runs int dec = 0, i = 0, rem;
i. while (n != 0) {
ii. rem = n % 10;
iii. n /= 10;
iv. dec += rem * pow(2, i);
v. ++i;
vi. }
4. From Decimal to Binary
a. User inputs string
b. String split and stored in integer array
c. (num%2==0) : either one or two
d. N=n/2
e. 4 times runs code and stored in backwards order
f. Output shown

Input :

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char bin[4][8];
int ipaddr[4];
if (!readBinary(bin));
convertBinToDec(bin, ipaddr);
printf("The address converted to decimal is: %d.%d.%d.%d\n", ipaddr[0],
ipaddr[1], ipaddr[2], ipaddr[3]);
}
int readBinary(char bin[4][8]) {
char binString[80];
int i, j;
int nextChar = 0;
int len;
printf("Enter 32-bit IP address in binary form : ");
fflush(stdout);
scanf("%[^\r\n]", binString);
len = strlen(binString);
for (i = 0; i < 4; i++) {
if (nextChar >= len) {
printf("Invalid input string (too short)\n");
return 0;
}
for (

Network and Communication : Lab FAT : 28-04-2022 17


CHEBROLU SAI PRASANNA ABHINAV – 20BCE2425

j = 0; j < 8; j++) {
while (nextChar < len && binString[nextChar] == ' ')
nextChar++;
if (nextChar >= len) {
printf("Invalid input string (too short)\n");
return 0;
}
bin[i][j] =
binString[nextChar];
nextChar++;
if (bin[i][j] != '0' && bin[i][j] != '1') {
printf("Invalid input string (not a binary number)\n");
return 0;
}
}
}
return 1;
}
int convertBinToDec(char bin[4][8], int dec[]) {
int i, j;
for (i = 0; i < 4; i++) {
dec[i] = 0;
for (j = 0; j < 8; j++) {
dec[i] *= 2;
if (bin[i][j] == '1')
dec[i]++;
}
}
}

Output :

3) Find the First address, Last address and Number of addresses from given IP address and Mask

Aim : To implement a program for First address, Last address and Number of addresses from IP
Address & Mask and display the output for a given input.

Input : Inputting the octet address with input lines

Code :

#include<stdio.h>
#include<stdlib.h>
int main() {
int ip[4];
int i;
for (i = 0; i < 4; i++) {

Network and Communication : Lab FAT : 28-04-2022 18


CHEBROLU SAI PRASANNA ABHINAV – 20BCE2425

printf("Enter the octet-%d: ", i);


scanf("%d", & ip[i]);
}
int p, s;
printf("Enter the prefix length:");
scanf("%d", & p);
int n;
printf("Enter the number of different blocks: ");
scanf("%d", & n);
int blocks[n][2];
for (i = 0; i < n; i++) {
printf("Enter the number of customers:");
scanf("%d", & blocks[i][0]);
printf("Enter the addresses for each customer: ");
scanf("%d", & blocks[i][1]);
}
s = 32 - p;
int x, ip2[4];
x = pow(2, s);
printf("The suffix length is: %d\n", s);
printf("The total number of addresses are: %d\n", x);
int a, j, k;
for (i = 0; i < n; i++) {
int a = log2(blocks[i][1]);
a = 32 - a;
printf("\n\n");
printf("The range of addresses in block: %d\n", i + 1);
for (j = 0; j < blocks[i][0]; j++) {
for (k = 0; k < 4; k++) {
ip2[k] = ip[k];
}
printf("%d.%d.%d.%d/%d - ", ip[0], ip[1], ip[2], ip[3], a);
for (k = 3; k >= 0; k--) {
if (ip2[k] >= 255) {
ip2[k] = 0;
ip2[k - 1] = ip2[k - 1] + 1;
}
}
ip2[3] = ip2[3] + blocks[i][1] - 1;
printf("%d.%d.%d.%d/%d", ip2[0], ip2[1], ip2[2], ip2[3], a);
printf("\n");
for (k = 0; k < 4; k++) {
ip[k] = ip2[k];
}
ip[3] = ip[3] + 1;
for (k = 3; k > 0; k--) {
if (ip[k] >= 255) {
ip[k - 1] = ip[k - 1] + 1;
}
}
}
}
int b = 0;

Network and Communication : Lab FAT : 28-04-2022 19


CHEBROLU SAI PRASANNA ABHINAV – 20BCE2425

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


b = b + (blocks[i][0] * blocks[i][1]);
}
x = x - b;
printf("\n");
printf("The remaining addresses are:%d", x);
}

Output :

4) Construct Various Subnet for an organization

Aim : To implement a program for constructing various subnet for an organization and display the
output for a given input.

Input : Inputting the octet address with input lines

Code :

#include <stdio.h>
#include <stdlib.h>
#include<string.h>
#include <math.h>
int main() {
char block[20], part[10] = "";
int i, j = 0, k = 0, num, sum = 0, sum2 = 0, sum3 = 0, dot = 0, a, b;
printf("Enter the block address in xxx.xxx.xxx.xxx/xx format: ");
scanf("%s", & block);
int len = strlen(block);
block[len] = 0;
while (block[k] != '.') {
num = block[k] - '0';
sum3 = (sum3 * 10) + num;
k++;
}
if (sum3 >= 0 && sum3 <= 127)

Network and Communication : Lab FAT : 28-04-2022 20


CHEBROLU SAI PRASANNA ABHINAV – 20BCE2425

b = 8;
if (sum3 >= 128 && sum3 <= 191)
b = 16;
if (sum3 >= 192 && sum3 <= 223)
b = 24;
while (dot < 3) {
if (block[j] == '.')
dot++;
j++;
}
a = j;
while (block[j] != '/') {
num = block[j] - '0';
sum = (sum * 10) + num;
j++;
}
j++;
while (block[j] != 0) {
num = block[j] - '0';
sum2 = (sum2 * 10) + num;
j++;
}
double y = 32 - sum2;
double diff = sum2 - b;
printf("\nThe number of subnets are: %.0lf", pow(2.0, diff));
long long convert(int n) {
long long bin = 0;
int rem, i = 1, step = 1;
while (n != 0) {
rem = n % 2;
step++;
n /= 2;
bin += rem * i;
i *= 10;
}
return bin;
}
int convert1(long long n) {
int dec = 0, i = 0, rem;
while (n != 0) {
rem = n % 10;
n /= 10;
dec += rem * pow(2, i);
++i;
}
return dec;
}
int x = convert(sum);
printf("\nThe starting address is: ");
for (i = 0; i < a; i++)
printf("%c", block[i]);
printf("%d", convert1(x - x % 10000));
printf("\nThe last address is: ");

Network and Communication : Lab FAT : 28-04-2022 21


CHEBROLU SAI PRASANNA ABHINAV – 20BCE2425

for (i = 0; i < a; i++)


printf("%c", block[i]);
printf("%d", convert1(x - x % 10000 + 1111));
printf("\nThe number of addresses in the block are: %.0lf", pow(2.0, y));
}

Output :

5a) Implement the Distance Vector Routing protocol

Aim : To implement a program for distance vector routing protocol and display the output for a
given input.

Algorithm :

Network and Communication : Lab FAT : 28-04-2022 22


CHEBROLU SAI PRASANNA ABHINAV – 20BCE2425

Input : Inputting the octet address with input lines

Code :

#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];//initialise the distance equal to cost matrix
rt[i].from[j]=j;
}
}
do
{
count=0;
for(i=0;i<nodes;i++)//We choose arbitary vertex k and we calculate the direct distance from
the node i to k using the cost matrix
//and add the distance from k to node j
for(j=0;j<nodes;j++)
for(k=0;k<nodes;k++)
if(rt[i].dist[j]>costmat[i][k]+rt[k].dist[j])
{//We calculate the minimum distance
rt[i].dist[j]=rt[i].dist[k]+rt[k].dist[j];
rt[i].from[j]=k;
count++;
}

Network and Communication : Lab FAT : 28-04-2022 23


CHEBROLU SAI PRASANNA ABHINAV – 20BCE2425

}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 :

5b) Implement the Link state routing protocol


Aim : To implement a program for link state routing protocol and display the output for a given
input.

Algorithm :

1. N = {A} // A is a root node.


2. for all nodes v
3. if v adjacent to A

Network and Communication : Lab FAT : 28-04-2022 24


CHEBROLU SAI PRASANNA ABHINAV – 20BCE2425

4. then D(v) = c(A,v)


5. else D(v) = infinity
6. loop
7. find w not in N such that D(w) is a minimum.
8. Add w to N
9. Update D(v) for all v adjacent to w and not in N:
10. D(v) = min(D(v) , D(w) + c(w,v))
11. Until all nodes in N

Input :

import java.util.*;
public class LSR
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of nodes : ");
int nodes = sc.nextInt();
int[] preD = new int[nodes];
int min = 999, nextNode = 0;
int[] distance = new int[nodes];
int[][] matrix = new int[nodes][nodes];
int[] visited = new int[nodes];
System.out.println("Enter the cost matrix");
for (int i = 0; i < distance.length; i++)
{
visited[i] = 0;
preD[i] = 0;
for (int j = 0; j < distance.length; j++)
{
matrix[i][j] = sc.nextInt();
if (matrix[i][j]==0)
matrix[i][j] = 999;
}
}
distance = matrix[0];
visited[0] = 1;
distance[0] = 0;
for (int counter = 0; counter < nodes; counter++)
{
min = 999;
for (int i = 0; i < nodes; i++)
{
if (min > distance[i] && visited[i]!=1)
{
min = distance[i];
nextNode = i;
}
}

visited[nextNode] = 1;
for (int i = 0; i < nodes; i++)

Network and Communication : Lab FAT : 28-04-2022 25


CHEBROLU SAI PRASANNA ABHINAV – 20BCE2425

{
if (visited[i]!=1)
{
if (min+matrix[nextNode][i] < distance[i])
{
distance[i] = min+matrix[nextNode][i];
preD[i] = nextNode;
}
}
}
}
int j;
for (int i = 0; i < nodes; i++)
{
if (i!=0)
{
System.out.print("Path = " + i);
j = i;
do
{
j = preD[j];
System.out.print(" <- " + j);
}
while(j != 0);
System.out.println();
System.out.print("Cost = " + distance[i]);
}
System.out.println("\n");

}
}
}

Output :

Input :

Network and Communication : Lab FAT : 28-04-2022 26


CHEBROLU SAI PRASANNA ABHINAV – 20BCE2425

#include <stdio.h>
#include <string.h>
int main()
{
int count,src_router,i,j,k,w,v,min;
int cost_matrix[100][100],dist[100],last[100];
int flag[100];
printf("\n Enter the no of routers");
scanf("%d",&count);
printf("\n Enter the cost matrix values:");
for(i=0;i<count;i++)
{
for(j=0;j<count;j++)
{
printf("\n%d->%d:",i,j);
scanf("%d",&cost_matrix[i][j]);
if(cost_matrix[i][j]<0)cost_matrix[i][j]=1000;
}
}
printf("\n Enter the source router:");
scanf("%d",&src_router);
for(v=0;v<count;v++)
{
flag[v]=0;
last[v]=src_router;
dist[v]=cost_matrix[src_router][v];
}
flag[src_router]=1;
for(i=0;i<count;i++)
{
min=1000;
for(w=0;w<count;w++)
{
if(!flag[w])
if(dist[w]<min)
{
v=w;
min=dist[w];
}
}
flag[v]=1;
for(w=0;w<count;w++)
{
if(!flag[w])
if(min+cost_matrix[v][w]<dist[w])
{
dist[w]=min+cost_matrix[v][w];
last[w]=v;
}
}
}
for(i=0;i<count;i++)
{

Network and Communication : Lab FAT : 28-04-2022 27


CHEBROLU SAI PRASANNA ABHINAV – 20BCE2425

printf("\n%d==>%d:Path taken:%d",src_router,i,i);
w=i;
while(w!=src_router)
{
printf("\n<--%d",last[w]);w=last[w];
}
printf("\n Shortest path cost:%d",dist[i]);
}
}

Output :

Network and Communication : Lab FAT : 28-04-2022 28


CHEBROLU SAI PRASANNA ABHINAV – 20BCE2425

Question Paper
1. Implement the following using socket switching program
a) Client Server Communication Using UDP
b) Client Server Communication Using TCP
c) Implement CHAT Application
d) Implement Security Protocol for Client Server Communication

1a) Client Server Communication using UDP

Aim : To implement a program for the Client Server Communication using UDP Mechanism and
display the output for a given input.

Algorithm :

8. Start.
9. UDP Server :
a) Create a UDP socket.
b) Bind the socket to the server address.
c) Wait until the datagram packet arrives from the client.
d) Process the datagram packet and send a reply to the client.
e) Go back to Step c.
10. UDP Client :
a) Create a UDP socket.
b) Send a message to the server.
c) Wait until response from the server is received.
d) Process reply and go back to step b, if necessary.
e) Close socket descriptor and exit.
11. End.

Server code :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
void main(int argc, char **argv){
if(argc != 2){
printf("Usage: %s <port>\n", argv[0]);
exit(0);
}
int port = atoi(argv[1]);
int sockfd;
struct sockaddr_in si_me, si_other;
char buffer[1024];
socklen_t addr_size;

sockfd = socket(AF_INET, SOCK_DGRAM, 0);


memset(&si_me, '\0', sizeof(si_me));
si_me.sin_family = AF_INET;

Network and Communication : Lab FAT : 28-04-2022 29


CHEBROLU SAI PRASANNA ABHINAV – 20BCE2425

si_me.sin_port = htons(port);
si_me.sin_addr.s_addr = inet_addr("127.0.0.1");
bind(sockfd, (struct sockaddr*)&si_me, sizeof(si_me));
addr_size = sizeof(si_other);
recvfrom(sockfd, buffer, 1024, 0, (struct sockaddr*)& si_other, &addr_size);
printf("[+]Data Received: %s", buffer);
}

Client Side
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
void main(int argc, char **argv){
if(argc != 2){
printf("Usage: %s <port>\n", argv[0]);
exit(0);
}
int port = atoi(argv[1]);
int sockfd;
struct sockaddr_in serverAddr;
char buffer[1024];
socklen_t addr_size;
sockfd = socket(PF_INET, SOCK_DGRAM, 0);
memset(&serverAddr, '\0', sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(port);
serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
strcpy(buffer, "Hello Server\n");
sendto(sockfd, buffer, 1024, 0, (struct sockaddr*)&serverAddr, sizeof(serverAddr));
printf("[+]Data Send: %s", buffer);
}

Contd…

Network and Communication : Lab FAT : 28-04-2022 30


CHEBROLU SAI PRASANNA ABHINAV – 20BCE2425

Output :

1b) Client Server Communication using TCP

Aim : To implement a program for the Client Server Communication using TCP Mechanism and
display the output for a given input.

Algorithm :

1. Start.
2. TCP Server –
a) using create(), Create TCP socket.
b) using bind(), Bind the socket to server address.
c) using listen(), put the server socket in a passive mode, where it waits for the client to
approach the server to make a connection
d) using accept(), At this point, connection is established between client and server, and
they are ready to transfer data.
e) Go back to Step c.

3. TCP Client –
a) Create TCP socket.
b) connect newly created client socket to server.
4. End.

Server code :
#include<stdio.h>
#include<netinet/in.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netdb.h>
#include<stdlib.h>
#include<string.h>
#define MAX 80
#define PORT 43454

Network and Communication : Lab FAT : 28-04-2022 31


CHEBROLU SAI PRASANNA ABHINAV – 20BCE2425

#define SA struct sockaddr


void func(int sockfd)
{
char buff[MAX];
int n;
for(;;)
{
bzero(buff,MAX);
read(sockfd,buff,sizeof(buff));
printf("From client: %s\t To client : ",buff);
bzero(buff,MAX);
n=0;
while((buff[n++]=getchar())!='\n');
write(sockfd,buff,sizeof(buff));
if(strncmp("exit",buff,4)==0)
{
printf("Server Exit...\n");
break;
}
}
}
int main()
{
int sockfd,connfd,len;
struct sockaddr_in servaddr,cli;
sockfd=socket(AF_INET,SOCK_STREAM,0);
if(sockfd==-1)
{
printf("socket creation failed...\n");
exit(0);
}
else
printf("Socket successfully created..\n");
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family=AF_INET;
servaddr.sin_addr.s_addr=htonl(INADDR_ANY);
servaddr.sin_port=htons(PORT);
if((bind(sockfd,(SA*)&servaddr, sizeof(servaddr)))!=0)
{
printf("socket bind failed...\n");
exit(0);
}
else
printf("Socket successfully binded..\n");
if((listen(sockfd,5))!=0)
{
printf("Listen failed...\n");
exit(0);
}
else
printf("Server listening..\n");
len=sizeof(cli);
connfd=accept(sockfd,(SA *)&cli,&len);

Network and Communication : Lab FAT : 28-04-2022 32


CHEBROLU SAI PRASANNA ABHINAV – 20BCE2425

if(connfd<0)
{
printf("server acccept failed...\n");
exit(0);
}
else
printf("server acccept the client...\n");
func(connfd);
close(sockfd);
}

Output :
./server

Client Side
#include<stdio.h>
#include<netinet/in.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netdb.h>
#include<string.h>
#include<stdlib.h>
#define MAX 80
#define PORT 43454
#define SA struct sockaddr
void func(int sockfd)
{
char buff[MAX];
int n;
for(;;)
{
bzero(buff,sizeof(buff));
printf("Enter the string : ");
n=0;
while((buff[n++]=getchar())!='\n');
write(sockfd,buff,sizeof(buff));
bzero(buff,sizeof(buff));
read(sockfd,buff,sizeof(buff));
printf("From Server : %s",buff);
if((strncmp(buff,"exit",4))==0)
{
printf("Client Exit...\n");
break;
}
}
}

Network and Communication : Lab FAT : 28-04-2022 33


CHEBROLU SAI PRASANNA ABHINAV – 20BCE2425

int main()
{
int sockfd,connfd;
struct sockaddr_in servaddr,cli;
sockfd=socket(AF_INET,SOCK_STREAM,0);
if(sockfd==-1)
{
printf("socket creation failed...\n");
exit(0);
}
else
printf("Socket successfully created..\n");
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family=AF_INET;
servaddr.sin_addr.s_addr=inet_addr("127.0.0.1");
servaddr.sin_port=htons(PORT);
if(connect(sockfd,(SA *)&servaddr,sizeof(servaddr))!=0)
{
printf("connection with the server failed...\n");
exit(0);
}
else
printf("connected to the server..\n");
func(sockfd);
close(sockfd);
}

Output :

./client

1c) Implementation of CHAT Application

Aim : To implement a program for the Client Server Communication using TCP Mechanism and
display the output for a given input.

Algorithm :

1. Start.
2. Server side
a) Declare the variables and structure for the socket.
b) Create a socket using socket functions
c) The socket is binded at the specified port.
d) Using the object the port and address are declared.
e) If the binding is successful write the message to the client.
f) Close the socket if the client sends a goodbye message.
g) Execute the client program.

Network and Communication : Lab FAT : 28-04-2022 34


CHEBROLU SAI PRASANNA ABHINAV – 20BCE2425

3. Client Side
a) Start the program.
b) Declare the variables and structure.
c) Socket is created and connects function is executed.
d) If the connection is successful then server sends the message.
e) The message from the server is responded by the client.
4. Stop the program

Server code :
import java.net.*;
import java.io.*;
import java.net.Socket;
public class chatserver {
public static void main(String args[]) throws Exception
{
ServerSocket ss=new ServerSocket(2000);
Socket sk=ss.accept();
BufferedReader cin=new BufferedReader(new InputStreamReader(sk.getInputStream()));
PrintStream cout=new PrintStream(sk.getOutputStream());
BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
String s;
while (true)
{
s=cin.readLine();
if (s.equalsIgnoreCase("END"))
{
cout.println("BYE");
break;
}
System. out.print("Client : "+s+"\n");
System.out.print("Server : ");
s=stdin.readLine();
cout.println(s);
}
ss.close();
sk.close();
cin.close();
cout.close();
stdin.close();
}
}

Output :
./server

Network and Communication : Lab FAT : 28-04-2022 35


CHEBROLU SAI PRASANNA ABHINAV – 20BCE2425

Client Side
import java.net.*;
import java.io.*;
public class chatclient {
public static void main(String args[]) throws Exception
{
Socket sk=new Socket("127.0.0.1",2000);
BufferedReader sin=new BufferedReader(new InputStreamReader(sk.getInputStream()));
PrintStream sout=new PrintStream(sk.getOutputStream());
BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
String s;
while (true)
{
System.out.print("Client : ");
s=stdin.readLine();
sout.println(s);
s=sin.readLine();
System.out.print("Server : "+s+"\n");
if (s.equalsIgnoreCase("BYE"))
break;
}
sk.close();
sin.close();
sout.close();
stdin.close();
}
}

Output :

1d) Implement Security Protocol for Client Server Communication

Aim : To implement a program for the Security Protocol for Client Server Communication
Mechanism and display the output for a given input.

Code :

Server code :
#include <string.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <errno.h>
#include <unistd.h>
#include <malloc.h>
#include <sys/types.h>

Network and Communication : Lab FAT : 28-04-2022 36


CHEBROLU SAI PRASANNA ABHINAV – 20BCE2425

#include <netinet/in.h>
#include <resolv.h>
#include "openssl/ssl.h"
#include "openssl/err.h"
#define FAIL -1
int OpenListener(int port)
{
int sd;
struct sockaddr_in addr;
sd = socket(PF_INET, SOCK_STREAM, 0);
bzero(&addr, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = INADDR_ANY;
if (bind(sd, (struct sockaddr*)&addr, sizeof(addr)) != 0 )
{
perror("can't bind port");
abort();
}
if ( listen(sd, 10) != 0 )
{
perror("Can't configure listening port");
abort();
}
return sd;
}
int isRoot()
{
if (getuid() != 0)
{
return 0;
}
else
{
return 1;
}
}
SSL_CTX* InitServerCTX(void)
{
SSL_METHOD *method;
SSL_CTX *ctx;
OpenSSL_add_all_algorithms();
SSL_load_error_strings();
method = TLSv1_2_server_method();
ctx = SSL_CTX_new(method);
if ( ctx == NULL )
{
ERR_print_errors_fp(stderr);
abort();
}
return ctx;
}
void LoadCertificates(SSL_CTX* ctx, char* CertFile, char* KeyFile)

Network and Communication : Lab FAT : 28-04-2022 37


CHEBROLU SAI PRASANNA ABHINAV – 20BCE2425

{
if ( SSL_CTX_use_certificate_file(ctx, CertFile, SSL_FILETYPE_PEM) <= 0 )
{
ERR_print_errors_fp(stderr);
abort();
}
if ( SSL_CTX_use_PrivateKey_file(ctx, KeyFile, SSL_FILETYPE_PEM) <= 0 )
{
ERR_print_errors_fp(stderr);
abort();
}
if ( !SSL_CTX_check_private_key(ctx) )
{
fprintf(stderr, "Private key does not match the public certificate\n");
abort();
}
}
void ShowCerts(SSL* ssl)
{
X509 *cert;
char *line;
cert = SSL_get_peer_certificate(ssl);
if ( cert != NULL )
{
printf("Server certificates:\n");
line = X509_NAME_oneline(X509_get_subject_name(cert), 0, 0);
printf("Subject: %s\n", line);
free(line);
line = X509_NAME_oneline(X509_get_issuer_name(cert), 0, 0);
printf("Issuer: %s\n", line);
free(line);
X509_free(cert);
}
else
printf("No certificates.\n");
}
void Servlet(SSL* ssl)
{
char buf[1024] = {0};
int sd, bytes;
const char* ServerResponse="<\Body>\
<Name>aticleworld.com</Name>\
<year>1.5</year>\
<BlogType>Embedede and c\c++<\BlogType>\
<Author>amlendra<Author>\
<\Body>";
const char *cpValidMessage = "<Body>\
<UserName>aticle<UserName>\
<Password>123<Password>\
<\Body>";
if ( SSL_accept(ssl) == FAIL )
ERR_print_errors_fp(stderr);
else

Network and Communication : Lab FAT : 28-04-2022 38


CHEBROLU SAI PRASANNA ABHINAV – 20BCE2425

{
ShowCerts(ssl);
bytes = SSL_read(ssl, buf, sizeof(buf));
buf[bytes] = '\0';
printf("Client msg: \"%s\"\n", buf);
if ( bytes > 0 )
{
if(strcmp(cpValidMessage,buf) == 0)
{
SSL_write(ssl, ServerResponse, strlen(ServerResponse));
}
else
{
SSL_write(ssl, "Invalid Message", strlen("Invalid Message"));
}
}
else
{
ERR_print_errors_fp(stderr);
}
}
sd = SSL_get_fd(ssl);
SSL_free(ssl);
close(sd);
}
int main(int count, char *Argc[])
{
SSL_CTX *ctx;
int server;
char *portnum;
if(!isRoot())
{
printf("This program must be run as root/sudo user!!");
exit(0);
}
if ( count != 2 )
{
printf("Usage: %s <portnum>\n", Argc[0]);
exit(0);
}
// Initialize the SSL library
SSL_library_init();
portnum = Argc[1];
ctx = InitServerCTX();
LoadCertificates(ctx, "mycert.pem", "mycert.pem");
server = OpenListener(atoi(portnum));
while (1)
{
struct sockaddr_in addr;
socklen_t len = sizeof(addr);
SSL *ssl;
int client = accept(server, (struct sockaddr*)&addr, &len);
printf("Connection: %s:%d\n",inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));

Network and Communication : Lab FAT : 28-04-2022 39


CHEBROLU SAI PRASANNA ABHINAV – 20BCE2425

ssl = SSL_new(ctx);
SSL_set_fd(ssl, client);
Servlet(ssl);
}
close(server);
SSL_CTX_free(ctx);
}

Output :

"<Body>
<Name>aticleworld.com</Name>
<year>1.5</year>
<BlogType>Embedede and c c++</BlogType>
<Author>amlendra</Author>
</Body>"

If the client sends an invalid request to the server then server give a response to an “Invalid
message”.

Client Side
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <malloc.h>
#include <string.h>
#include <sys/socket.h>
#include <resolv.h>
#include <netdb.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#define FAIL -1
int OpenConnection(const char *hostname, int port)
{
int sd;
struct hostent *host;
struct sockaddr_in addr;
if ( (host = gethostbyname(hostname)) == NULL )
{
perror(hostname);
abort();
}
sd = socket(PF_INET, SOCK_STREAM, 0);
bzero(&addr, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = *(long*)(host->h_addr);
if ( connect(sd, (struct sockaddr*)&addr, sizeof(addr)) != 0 )
{
close(sd);
perror(hostname);

Network and Communication : Lab FAT : 28-04-2022 40


CHEBROLU SAI PRASANNA ABHINAV – 20BCE2425

abort();
}
return sd;
}
SSL_CTX* InitCTX(void)
{
SSL_METHOD *method;
SSL_CTX *ctx;
OpenSSL_add_all_algorithms();
SSL_load_error_strings();
method = TLSv1_2_client_method();
ctx = SSL_CTX_new(method);
if ( ctx == NULL )
{
ERR_print_errors_fp(stderr);
abort();
}
return ctx;
}
void ShowCerts(SSL* ssl)
{
X509 *cert;
char *line;
cert = SSL_get_peer_certificate(ssl);
if ( cert != NULL )
{
printf("Server certificates:\n");
line = X509_NAME_oneline(X509_get_subject_name(cert), 0, 0);
printf("Subject: %s\n", line);
free(line);
line = X509_NAME_oneline(X509_get_issuer_name(cert), 0, 0);
printf("Issuer: %s\n", line);
free(line);
X509_free(cert
}
else
printf("Info: No client certificates configured.\n");
}
int main(int count, char *strings[])
{
SSL_CTX *ctx;
int server;
SSL *ssl;
char buf[1024];
char acClientRequest[1024] = {0};
int bytes;
char *hostname, *portnum;
if ( count != 3 )
{
printf("usage: %s <hostname> <portnum>\n", strings[0]);
exit(0);
}
SSL_library_init();

Network and Communication : Lab FAT : 28-04-2022 41


CHEBROLU SAI PRASANNA ABHINAV – 20BCE2425

hostname=strings[1];
portnum=strings[2];
ctx = InitCTX();
server = OpenConnection(hostname, atoi(portnum));
ssl = SSL_new(ctx);
SSL_set_fd(ssl, server);
if ( SSL_connect(ssl) == FAIL )
ERR_print_errors_fp(stderr);
else
{
char acUsername[16] = {0};
char acPassword[16] = {0};
const char *cpRequestMessage = "<Body>\
<UserName>%s<UserName>\
<Password>%s<Password>\
<\Body>";
printf("Enter the User Name : ");
scanf("%s",acUsername);
printf("\n\nEnter the Password : ");
scanf("%s",acPassword);
sprintf(acClientRequest, cpRequestMessage, acUsername,acPassword);
printf("\n\nConnected with %s encryption\n", SSL_get_cipher(ssl));
ShowCerts(ssl);
SSL_write(ssl,acClientRequest, strlen(acClientRequest));
bytes = SSL_read(ssl, buf, sizeof(buf));
buf[bytes] = 0;
printf("Received: \"%s\"\n", buf);
SSL_free(ssl);
}
close(server);
SSL_CTX_free(ctx);
return 0;
}

Output :

"<Body>
<UserName>amlendra</UserName>
<Password>1235</Password>
</Body>"

Server Response:
“Invalid Message”

Network and Communication : Lab FAT : 28-04-2022 42


CHEBROLU SAI PRASANNA ABHINAV – 20BCE2425

Question Paper
A) Study about Networking Commands.
B) Implement the following Error Control Mechanism
i) CRC
ii) Checksum

1A) Network Commands

1. Ping
The ping command is used to check if a remote system is running or up. In short this command is used
to detect whether a system is connected to the network or not.
The ping command (named after the sound of an active sonar system) sends echo requests to the host
specified on the command line, and lists the responses received.
• ping - sends an ICMP ECHO_REQUEST packet to the specified host. If the host responds, an ICMP
packet is received.
• One can “ping” an IP address to see if a machine is alive.
• It provides a very quick way to see if a machine is up and connected to the network.

Syntax : ping <ip address> or <hostname>


abhinavchebrolu@AbhinavChebrolu-VB:~$ ping www.gonav.in
PING gonav.in (3.33.152.147) 56(84) bytes of data.
64 bytes from a4ec4c6ea1c92e2e6.awsglobalaccelerator.com (3.33.152.147): icmp_seq=1 ttl=118 time=21.3 ms
64 bytes from a4ec4c6ea1c92e2e6.awsglobalaccelerator.com (3.33.152.147): icmp_seq=2 ttl=118 time=21.7 ms
64 bytes from a4ec4c6ea1c92e2e6.awsglobalaccelerator.com (3.33.152.147): icmp_seq=3 ttl=118 time=21.4 ms
64 bytes from a4ec4c6ea1c92e2e6.awsglobalaccelerator.com (3.33.152.147): icmp_seq=4 ttl=118 time=21.3 ms
64 bytes from a4ec4c6ea1c92e2e6.awsglobalaccelerator.com (3.33.152.147): icmp_seq=5 ttl=118 time=21.3 ms
^Z
[4]+ Stopped ping www.gonav.in

2. Hostname
This is the simplest of all TCP/IP commands. It simply displays the name of your computer. hostname
command in Linux is used to obtain the DNS(Domain Name System) name and set the system’s
hostname or NIS(Network Information System) domain name. A hostname is a name which is given to
a computer and it attached to the network. Its main purpose is to uniquely identify over a network.
Syntax : hostname

abhinavchebrolu@AbhinavChebrolu-VB:~$ hostname
AbhinavChebrolu-VB

Network and Communication : Lab FAT : 28-04-2022 43


CHEBROLU SAI PRASANNA ABHINAV – 20BCE2425

3. Traceroute
traceroute will show the route of a packet. It attempts to list the series of hosts through which our
packets travel on their way to a given destination. It is an Linux prints the route that a packet takes to
reach the host. This command is useful when you want to know about the route and about all the hops
that a packet takes
Syntax : traceroute <ip address> or <hostname>
abhinavchebrolu@AbhinavChebrolu-VB:~$ traceroute www.gonav.in
traceroute to www.gonav.in (3.33.152.147), 30 hops max, 60 byte packets
1 _gateway (10.0.2.2) 1.349 ms 1.307 ms 1.279 ms
2 _gateway (10.0.2.2) 62.902 ms 64.914 ms 60.618 ms

4. tracepath
Similar to traceroute but doesn't require root privileges. tracepath command in Linux is used to traces
path to destination discovering MTU along this path. It uses UDP port or some random port. It is similar
to traceroute, but it does not require superuser privileges and has no fancy options
Syntax : tracepath <ip address> or <hostname>
abhinavchebrolu@AbhinavChebrolu-VB:~$ tracepath www.gonav.in
1?: [LOCALHOST] pmtu 1500
1: _gateway 0.757ms
1: _gateway 0.347ms
2: _gateway 396.697ms reached
Resume: pmtu 1500 hops 2 back 1

5. ifconfig
ifconfig(interface configuration) command is used to configure the kernel-resident network interfaces. It
is used at the boot time to set up the interfaces as necessary. After that, it is usually used when needed
during debugging or when you need system tuning. Also, this command is used to assign the IP address
and netmask to an interface or to enable or disable a given interface.

Syntax : ifconfig lo
abhinavchebrolu@AbhinavChebrolu-VB:~$ ifconfig lo
lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536
inet 127.0.0.1 netmask 255.0.0.0
inet6 ::1 prefixlen 128 scopeid 0x10<host>
loop txqueuelen 1000 (Local Loopback)
RX packets 417 bytes 38947 (38.9 KB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 417 bytes 38947 (38.9 KB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0

Network and Communication : Lab FAT : 28-04-2022 44


CHEBROLU SAI PRASANNA ABHINAV – 20BCE2425

6. netstat
This command helps solve problems with NetBIOS name resolution. (Nbt stands for NetBIOS over
TCP/IP) Definitions. displays various network related information such as network connections, routing
tables, interface statistics, masquerade connections, multicast memberships etc.
Syntax : netstat
abhinavchebrolu@AbhinavChebrolu-VB:~$ netstat
Active Internet connections (w/o servers)
Proto Recv-Q Send-Q Local Address Foreign Address State
udp 0 0 AbhinavChebrolu-:bootpc _gateway:bootps ESTABLISHED
Active UNIX domain sockets (w/o servers)
Proto RefCnt Flags Type State I-Node Path
unix 2 [ ] DGRAM 28120 /run/user/1000/systemd/notify
unix 3 [ ] DGRAM 15478 /run/systemd/notify
unix 2 [ ] DGRAM 15492 /run/systemd/journal/syslog
unix 15 [ ] DGRAM 15502 /run/systemd/journal/dev-log
unix 8 [ ] DGRAM 15506 /run/systemd/journal/socket
unix 3 [ ] STREAM CONNECTED 32425 @/tmp/dbus-sbNhHnkbT1
unix 3 [ ] STREAM CONNECTED 31612
unix 3 [ ] STREAM CONNECTED 33253 /run/user/1000/bus
unix 3 [ ] STREAM CONNECTED 31909 /run/systemd/journal/stdout
unix 3 [ ] STREAM CONNECTED 28824 @/tmp/.X11-unix/X0
unix 3 [ ] STREAM CONNECTED 32668
unix 3 [ ] STREAM CONNECTED 32337 /run/dbus/system_bus_socket
unix 3 [ ] STREAM CONNECTED 32220 /run/systemd/journal/stdout
unix 3 [ ] STREAM CONNECTED 29158 /run/dbus/system_bus_socket
unix 3 [ ] STREAM CONNECTED 32098
unix 3 [ ] STREAM CONNECTED 28554
unix 2 [ ] DGRAM 70595
unix 3 [ ] STREAM CONNECTED 27271 /run/systemd/journal/stdout
unix 3 [ ] STREAM CONNECTED 27227
unix 3 [ ] STREAM CONNECTED 32623 /run/systemd/journal/stdout
unix 3 [ ] STREAM CONNECTED 30639
unix 3 [ ] STREAM CONNECTED 29441
unix 2 [ ] STREAM CONNECTED 24582
unix 3 [ ] STREAM CONNECTED 22473 /run/systemd/journal/stdout
unix 3 [ ] STREAM CONNECTED 31351 /run/user/1000/bus
unix 3 [ ] STREAM CONNECTED 29275 @/tmp/.X11-unix/X0
unix 3 [ ] STREAM CONNECTED 21299 /run/systemd/journal/stdout
unix 2 [ ] DGRAM 70049
unix 3 [ ] STREAM CONNECTED 27226
unix 3 [ ] STREAM CONNECTED 79138
unix 3 [ ] STREAM CONNECTED 32205 /run/systemd/journal/stdout
unix 3 [ ] STREAM CONNECTED 30876
unix 3 [ ] STREAM CONNECTED 27129 /run/systemd/journal/stdout
unix 3 [ ] STREAM CONNECTED 30022 /run/systemd/journal/stdout
unix 3 [ ] STREAM CONNECTED 27379 /run/systemd/journal/stdout
.
.
.
. (it continues)

Network and Communication : Lab FAT : 28-04-2022 45


CHEBROLU SAI PRASANNA ABHINAV – 20BCE2425

7. netstat -s
To list the statistics for all ports.
Syntax : netstat -s
abhinavchebrolu@AbhinavChebrolu-VB:~$ netstat -s
Ip:
Forwarding: 2
6728 total packets received
1 with invalid addresses
0 forwarded
0 incoming packets discarded
6725 incoming packets delivered
6241 requests sent out
20 outgoing packets dropped
Icmp:
61 ICMP messages received
1 input ICMP message failed
ICMP input histogram:
destination unreachable: 56
timeout in transit: 5
42 ICMP messages sent
0 ICMP messages failed
ICMP output histogram:
destination unreachable: 42
IcmpMsg:
InType3: 56
InType11: 5
OutType3: 42
Tcp:
76 active connection openings
0 passive connection openings

Network and Communication : Lab FAT : 28-04-2022 46


CHEBROLU SAI PRASANNA ABHINAV – 20BCE2425

2 failed connection attempts


5 connection resets received
0 connections established
6041 segments received
5538 segments sent out
21 segments retransmitted
0 bad segments received
27 resets sent
Udp:
579 packets received
42 packets to unknown port received
0 packet receive errors
647 packets sent
0 receive buffer errors
0 send buffer errors
IgnoredMulti: 4
UdpLite:
TcpExt:
28 TCP sockets finished time wait in fast timer
13 delayed acks sent
Quick ack mode was activated 1 times
5361 packet headers predicted
70 acknowledgments not containing data payload received
187 predicted acknowledgments
TCPLostRetransmit: 11
TCPTimeouts: 21
5 connections reset due to early user close
TCPRcvCoalesce: 18
TCPAutoCorking: 17
TCPSynRetrans: 21
TCPOrigDataSent: 262
TCPDelivered: 322
TcpTimeoutRehash: 21
IpExt:
InMcastPkts: 79
OutMcastPkts: 81
InBcastPkts: 4
OutBcastPkts: 4
InOctets: 38875776
OutOctets: 376482
InMcastOctets: 7432
OutMcastOctets: 7512
InBcastOctets: 310
OutBcastOctets: 310
InNoECTPkts: 27702
MPTcpExt:

|
|
|
|
|

Network and Communication : Lab FAT : 28-04-2022 47


CHEBROLU SAI PRASANNA ABHINAV – 20BCE2425

8. dig
Query DNS related information. dig command stands for Domain Information Groper. It is used for
retrieving information about DNS name servers. It is basically used by network administrators. It is used
for verifying and troubleshooting DNS problems and to perform DNS lookups. Dig command replaces
older tools such as nslookup and the host.
Syntax : dig <ip address>
abhinavchebrolu@AbhinavChebrolu-VB:~$ dig www.gonav.in

; <<>> DiG 9.16.1-Ubuntu <<>> www.gonav.in


;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 59282
;; flags: qr rd ra; QUERY: 1, ANSWER: 3, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 65494

Network and Communication : Lab FAT : 28-04-2022 48


CHEBROLU SAI PRASANNA ABHINAV – 20BCE2425

;; QUESTION SECTION:
;www.gonav.in. IN A

;; ANSWER SECTION:
www.gonav.in. 1665 IN CNAME gonav.in.
gonav.in. 600 IN A 15.197.142.173
gonav.in. 600 IN A 3.33.152.147

;; Query time: 191 msec


;; SERVER: 127.0.0.53#53(127.0.0.53)
;; WHEN: Fri Jan 07 19:13:03 IST 2022
;; MSG SIZE rcvd: 87

9. nslookup
Nslookup is used for diagnosing DNS problems. If you can access a resource by specifying an IP address
but not it’s DNS you have a DNS problem. (stands for “Name Server Lookup”) is a useful command for
getting information from the DNS server. It is a network administration tool for querying the Domain
Name System (DNS) to obtain domain name or IP address mapping or any other specific DNS record. It
is also used to troubleshoot DNS-related problems.
Syntax : nslookup <ip address>
abhinavchebrolu@AbhinavChebrolu-VB:~$ nslookup www.gonav.in
Server: 127.0.0.53
Address: 127.0.0.53#53

Non-authoritative answer:
www.gonav.in canonical name = gonav.in.
Name: gonav.in
Address: 3.33.152.147
Name: gonav.in
Address: 15.197.142.173

|
|

Network and Communication : Lab FAT : 28-04-2022 49


CHEBROLU SAI PRASANNA ABHINAV – 20BCE2425

10. host
Performs DNS lookups. host command in Linux system is used for DNS (Domain Name System) lookup
operations. In simple words, this command is used to find the IP address of a particular domain name or
if you want to find out the domain name of a particular IP address the host command becomes handy.
You can also find more specific details of a domain by specifying the corresponding option along with the
domain name.
Syntax : host <ip address>
abhinavchebrolu@AbhinavChebrolu-VB:~$ host www.gonav.in
www.gonav.in is an alias for gonav.in.
gonav.in has address 3.33.152.147
gonav.in has address 15.197.142.173
gonav.in mail is handled by 10 alt3.aspmx.l.google.com.
gonav.in mail is handled by 10 alt4.aspmx.l.google.com.
gonav.in mail is handled by 1 aspmx.l.google.com.
gonav.in mail is handled by 5 alt1.aspmx.l.google.com.
gonav.in mail is handled by 5 alt2.aspmx.l.google.com.

11. arp
View or add contents of the kernel's ARP table. arp command manipulates the System’s ARP cache. It
also allows a complete dump of the ARP cache. ARP stands for Address Resolution Protocol. The primary
function of this protocol is to resolve the IP address of a system to its mac address, and hence it works
between level 2(Data link layer) and level 3(Network layer).
Syntax : arp
abhinavchebrolu@AbhinavChebrolu-VB:~$ arp
Address HWtype HWaddress Flags Mask Iface
_gateway ether 52:54:00:12:35:02 C enp0s3

12. iwconfig
Used to configure wireless network interface. iwconfig command in Linux is like ifconfig command, in the
sense it works with kernel-resident network interface but it is dedicated to wireless networking
interfaces only. It is used to set the parameters of the network interface that are particular to the wireless

Network and Communication : Lab FAT : 28-04-2022 50


CHEBROLU SAI PRASANNA ABHINAV – 20BCE2425

operation like SSID, frequency etc. iwconfig may also be used to display the parameters, and the wireless
statistics which are extracted from /proc/net/wireless.
Syntax : iwconfig [interface] [options]
abhinavchebrolu@AbhinavChebrolu-VB:~$ iwconfig
lo no wireless extensions.

enp0s3 no wireless extensions.

13. mtr

Combines ping and tracepath into a single command. mtr command is a combination of ping and
traceroute commands. It is a network diagnostic tool that continuously sends packets showing ping time
for each hop. It also displays network problems of the entire route taken by the network packets
Syntax : mtr <ip address>

abhinavchebrolu@AbhinavChebrolu-VB:~$ mtr www.gonav.in

14. whois
Will tell you about the website's whois or it is a command is a query and response protocol, used to fetch
the contact details, creation and expiration date, address of the registered domains, websites and IP
address.
Syntax : whois <ip address>
abhinavchebrolu@AbhinavChebrolu-VB:~$ whois gonav.in
Domain Name: gonav.in
Registry Domain ID: D86F6C21FE2C9480287C20AA7F9218CF1-IN
Registrar WHOIS Server:
Registrar URL: www.godaddy.com
Updated Date: 2021-05-13T13:43:38Z
Creation Date: 2021-05-08T13:43:37Z
Registry Expiry Date: 2023-05-08T13:43:37Z
Registrar: GoDaddy.com, LLC
Registrar IANA ID: 146
Registrar Abuse Contact Email:
Registrar Abuse Contact Phone:
Domain Status: clientRenewProhibited http://www.icann.org/epp#clientRenewProhibited
Domain Status: clientUpdateProhibited http://www.icann.org/epp#clientUpdateProhibited
Domain Status: clientTransferProhibited http://www.icann.org/epp#clientTransferProhibited
Domain Status: clientDeleteProhibited http://www.icann.org/epp#clientDeleteProhibited
Registry Registrant ID: REDACTED FOR PRIVACY
Registrant Name: REDACTED FOR PRIVACY
Registrant Organization: GoNav

Network and Communication : Lab FAT : 28-04-2022 51


CHEBROLU SAI PRASANNA ABHINAV – 20BCE2425

Registrant Street: REDACTED FOR PRIVACY


Registrant Street: REDACTED FOR PRIVACY
Registrant Street: REDACTED FOR PRIVACY
Registrant City: REDACTED FOR PRIVACY
Registrant State/Province: Andhra Pradesh
Registrant Postal Code: REDACTED FOR PRIVACY
Registrant Country: IN
Registrant Phone: REDACTED FOR PRIVACY
Registrant Phone Ext: REDACTED FOR PRIVACY
Registrant Fax: REDACTED FOR PRIVACY
Registrant Fax Ext: REDACTED FOR PRIVACY
Registrant Email: Please contact the Registrar listed above
Registry Admin ID: REDACTED FOR PRIVACY
Admin Name: REDACTED FOR PRIVACY
Admin Organization: REDACTED FOR PRIVACY
Admin Street: REDACTED FOR PRIVACY
Admin Street: REDACTED FOR PRIVACY
Admin Street: REDACTED FOR PRIVACY
Admin City: REDACTED FOR PRIVACY
Admin State/Province: REDACTED FOR PRIVACY
Admin Postal Code: REDACTED FOR PRIVACY
Admin Country: REDACTED FOR PRIVACY
Admin Phone: REDACTED FOR PRIVACY
Admin Phone Ext: REDACTED FOR PRIVACY
Admin Fax: REDACTED FOR PRIVACY
Admin Fax Ext: REDACTED FOR PRIVACY
Admin Email: Please contact the Registrar listed above
Registry Tech ID: REDACTED FOR PRIVACY
Tech Name: REDACTED FOR PRIVACY
Tech Organization: REDACTED FOR PRIVACY
Tech Street: REDACTED FOR PRIVACY
Tech Street: REDACTED FOR PRIVACY
Tech Street: REDACTED FOR PRIVACY
Tech City: REDACTED FOR PRIVACY
Tech State/Province: REDACTED FOR PRIVACY
Tech Postal Code: REDACTED FOR PRIVACY
Tech Country: REDACTED FOR PRIVACY
Tech Phone: REDACTED FOR PRIVACY
Tech Phone Ext: REDACTED FOR PRIVACY
Tech Fax: REDACTED FOR PRIVACY
Tech Fax Ext: REDACTED FOR PRIVACY
Tech Email: Please contact the Registrar listed above
Name Server: ns59.domaincontrol.com
Name Server: ns60.domaincontrol.com
DNSSEC: unsigned
URL of the ICANN Whois Inaccuracy Complaint Form: https://www.icann.org/wicf/
>>> Last update of WHOIS database: 2022-01-07T13:56:17Z <<<

For more information on Whois status codes, please visit https://icann.org/epp

|
|
|
|
|
|
|
|

Network and Communication : Lab FAT : 28-04-2022 52


CHEBROLU SAI PRASANNA ABHINAV – 20BCE2425

15. ifplugstatus

This command tells us whether a cable is plugged into our network interface or not. By default, it is not
installed in Ubuntu, to install it use command sudo apt-get install ifplugd.
Syntax : ifplugstatus

abhinavchebrolu@AbhinavChebrolu-VB:~$ ifplugstatus
lo: link beat detected
enp0s3: link beat detected

16. uptime
Uptime Command In Linux: It is used to find out how long the system is active (running). This command
returns set of values that involve, the current time, and the amount of time system is in running state,
number of users currently logged into, and the load time for the past 1, 5 and 15 minutes respectively.
Syntax : uptime

abhinavchebrolu@AbhinavChebrolu-VB:~$ uptime
19:30:18 up 1:06, 1 user, load average: 0.08, 0.11, 0.09

17. free
The free command provides information about the total amount of the physical and swap memory, as
well as the free and used memory. When used without any option, the free command will display
information about the memory and swap in kibibyte. 1 kibibyte (KiB) is 1024 bytes.
Syntax : free
abhinavchebrolu@AbhinavChebrolu-VB:~$ free
total used free shared buff/cache available
Mem: 2027824 937976 200336 17748 889512 917356

Network and Communication : Lab FAT : 28-04-2022 53


CHEBROLU SAI PRASANNA ABHINAV – 20BCE2425

18. last
The last command in Linux is used to display the list of all the users logged in and out since the file
/var/log/wtmp was created. One or more usernames can be given as an argument to display their login
in (and out) time and their host-name.
Syntax : last
abhinavchebrolu@AbhinavChebrolu-VB:~$ last
abhinavc :0 :0 Fri Jan 7 18:25 still logged in
reboot system boot 5.11.0-44-generi Fri Jan 7 18:24 still running
abhinavc :0 :0 Thu Jan 6 20:10 - crash (22:13)
reboot system boot 5.11.0-44-generi Thu Jan 6 20:09 still running
abhinavc :0 :0 Thu Jan 6 17:56 - down (02:12)
reboot system boot 5.11.0-27-generi Thu Jan 6 17:55 - 20:08 (02:13)
abhinavc :0 :0 Mon Dec 6 13:47 - crash (31+04:08)
reboot system boot 5.11.0-27-generi Mon Dec 6 13:45 - 20:08 (31+06:23)
abhinavc :0 :0 Mon Nov 22 14:04 - crash (13+23:41)
reboot system boot 5.11.0-27-generi Mon Nov 22 14:02 - 20:08 (45+06:05)
abhinavc :0 :0 Mon Nov 22 10:40 - crash (03:22)
reboot system boot 5.11.0-27-generi Mon Nov 22 10:38 - 20:08 (45+09:29)
abhinavc :0 :0 Sun Nov 7 13:29 - crash (14+21:09)
reboot system boot 5.11.0-27-generi Sun Nov 7 13:28 - 20:08 (60+06:40)

19. ps
Linux provides us a utility called ps for viewing information related with the processes on a system which
stands as abbreviation for “Process Status”. ps command is used to list the currently running processes
and their PIDs along with some other information depends on different options. It reads the process
information from the virtual files in /proc file-system. /proc contains virtual files, this is the reason it’s
referred as a virtual file system.
Syntax : ps
abhinavchebrolu@AbhinavChebrolu-VB:~$ ps
PID TTY TIME CMD
13445 pts/0 00:00:00 bash
14764 pts/0 00:00:00 ps

20. df
The df command (short for disk free), is used to display information related to file systems about total
space and available space.

Network and Communication : Lab FAT : 28-04-2022 54


CHEBROLU SAI PRASANNA ABHINAV – 20BCE2425

Syntax : df
abhinavchebrolu@AbhinavChebrolu-VB:~$ df
Filesystem 1K-blocks Used Available Use% Mounted on
udev 981176 0 981176 0% /dev
tmpfs 202784 1448 201336 1% /run
/dev/sda5 19992176 9687644 9265940 52% /
tmpfs 1013912 0 1013912 0% /dev/shm
tmpfs 5120 4 5116 1% /run/lock
tmpfs 1013912 0 1013912 0% /sys/fs/cgroup
/dev/loop4 128 128 0 100% /snap/bare/5
/dev/loop1 56832 56832 0 100% /snap/core18/2246
/dev/loop0 63360 63360 0 100% /snap/core20/1242
/dev/loop5 224256 224256 0 100% /snap/gnome-3-34-1804/72
/dev/loop2 63488 63488 0 100% /snap/core20/1270
/dev/loop7 253952 253952 0 100% /snap/gnome-3-38-2004/87
/dev/loop6 224256 224256 0 100% /snap/gnome-3-34-1804/77
/dev/loop3 56832 56832 0 100% /snap/core18/2253
/dev/loop8 66688 66688 0 100% /snap/gtk-common-themes/1515
/dev/loop10 52224 52224 0 100% /snap/snap-store/547
/dev/loop12 43264 43264 0 100% /snap/snapd/14066
/dev/loop13 55552 55552 0 100% /snap/snap-store/558
/dev/loop9 66816 66816 0 100% /snap/gtk-common-themes/1519
/dev/loop11 44416 44416 0 100% /snap/snapd/14295
/dev/sda1 523248 912 522336 1% /boot/efi
Oracle_Sharedfolder 464628732 86730364 377898368 19% /media/sf_Oracle_Sharedfolder
tmpfs 202780 36 202744 1% /run/user/1000

21. cat
Cat(concatenate) command is very frequently used in Linux. It reads data from the file and gives their
content as output. It helps us to create, view, concatenate files. So let us see some frequently used cat
commands.
Syntax : cat
abhinavchebrolu@AbhinavChebrolu-VB:~$ cat
Abhinav
Abhinav

Network and Communication : Lab FAT : 28-04-2022 55


CHEBROLU SAI PRASANNA ABHINAV – 20BCE2425

22. tcpdump
tcpdump is a packet sniffing and packet analyzing tool for a System Administrator to troubleshoot
connectivity issues in Linux. It is used to capture, filter, and analyze network traffic such as TCP/IP
packets going through your system. It is many times used as a security tool as well. It saves the captured
information in a pcap file, these pcap files can then be opened through Wireshark or through the
command tool itself.
Syntax : tcpdump
abhinavchebrolu@AbhinavChebrolu-VB:~$ tcpdump
tcpdump: enp0s3: You don't have permission to capture on that device
(socket: Operation not permitted)

23. finger
Retrieves information about specified user : Finger command is a user information lookup command
which gives details of all the users logged in. This tool is generally used by system administrators. It
provides details like login name, user name, idle time, login time, and in some cases their email address
even. This tool is similar to the Pinky tool but the Pinky tool is just the lightweight version of this tool.
Syntax : finger <hostname>
abhinavchebrolu@AbhinavChebrolu-VB:~$ finger abhinavchebrolu
Login: abhinavchebrolu Name: Abhinav Chebrolu
Directory: /home/abhinavchebrolu Shell: /bin/bash
On since Sun Jan 23 13:01 (IST) on :0 from :0 (messages off)
No mail.
No Plan.

24. telnet
telnet command is used to create a remote connection with a system over a TCP/IP network. It allows
us to administrate other systems by the terminal. We can run a program to conduct administration.
Syntax : telnet <ip address>
abhinavchebrolu@AbhinavChebrolu-VB:~$ telnet gonav.in
Trying 15.197.142.173...
Trying 3.33.152.147...
telnet: Unable to connect to remote host: Connection timed out

25. ftp

Network and Communication : Lab FAT : 28-04-2022 56


CHEBROLU SAI PRASANNA ABHINAV – 20BCE2425

ftp is the user interface to the Internet standard File Transfer Protocol. The program allows a user to
transfer files to and from a remote network site.
Syntax : ftp <ip address>
abhinavchebrolu@AbhinavChebrolu-VB:~$ ftp gonav.in
ftp: connect to address 3.33.152.147: Connection timed out
Trying 15.197.142.173...
ftp: connect: Connection timed out

26. SS
The ss (socket statistics) tool is a CLI command used to show network statistics. The ss command is a
simpler and faster version of the now obsolete netstat command. Together with the ip command, ss is
essential for gathering network information and troubleshooting network issues.
Syntax : ss
abhinavchebrolu@AbhinavChebrolu-VB:~$ ss
Netid State Recv-Q Send-Q Local Address:Port Peer Address:Port
Process
u_str ESTAB 0 0 * 62891 * 62892
u_str ESTAB 0 0 * 41027 * 40580
u_str ESTAB 0 0 * 38312 * 38961
u_str ESTAB 0 0 @/tmp/.X11-unix/X0 40799 * 40798
u_str ESTAB 0 0 /run/systemd/journal/stdout 23844 * 23842
u_str ESTAB 0 0 /run/user/1000/bus 38258 * 37884
u_str ESTAB 0 0 @/tmp/.X11-unix/X0 36537 * 36536
u_str ESTAB 0 0 * 35616 * 34601
u_str ESTAB 0 0 /run/systemd/journal/stdout 35114 * 34329
u_str ESTAB 0 0 * 40874 * 40876
u_str ESTAB 0 0 * 39653 * 41041
u_str ESTAB 0 0 /run/dbus/system_bus_socket 34236 * 35036
u_str ESTAB 0 0 * 33632 * 33633
u_str ESTAB 0 0 * 27801 * 27800
u_str ESTAB 0 0 /run/systemd/journal/stdout 39147 * 39999
u_str ESTAB 0 0 * 41170 * 41171
u_str ESTAB 0 0 * 40257 * 40258
u_str ESTAB 0 0 /run/dbus/system_bus_socket 24639 * 24128
u_str ESTAB 0 0 /run/dbus/system_bus_socket 43955 * 43004
u_str ESTAB 0 0 /run/user/1000/bus 41120 * 40789
u_str ESTAB 0 0 * 62946 * 62947
u_str ESTAB 0 0 * 40506 * 41039
u_str ESTAB 0 0 * 24127 * 24637
u_str ESTAB 0 0 * 41232 * 40828
u_str ESTAB 0 0 * 41070 * 40779
u_str ESTAB 0 0 * 34651 * 34652
u_str ESTAB 0 0 * 41438 * 40879
u_str ESTAB 0 0 /run/systemd/journal/stdout 41226 * 41225
u_str ESTAB 0 0 * 39052 * 38461
u_str ESTAB 0 0 * 41348 * 41349
u_str ESTAB 0 0 * 26578 * 26667
u_str ESTAB 0 0 * 22859 * 23847
u_str ESTAB 0 0 * 26824 * 26613
u_str ESTAB 0 0 * 40825 * 40826

Network and Communication : Lab FAT : 28-04-2022 57


CHEBROLU SAI PRASANNA ABHINAV – 20BCE2425

27. arp -a
arp command manipulates the System’s ARP cache. It also allows a complete dump of the ARP cache.
ARP stands for Address Resolution Protocol. The primary function of this protocol is to resolve the IP
address of a system to its mac address, and hence it works between level 2(Data link layer) and level
3(Network layer).
Syntax : arp -a

abhinavchebrolu@AbhinavChebrolu-VB:~$ arp -a
_gateway (10.0.2.2) at 52:54:00:12:35:02 [ether] on enp0s3

28. curl
curl is a free command-line utility for transferring data from or to a server designed to work without user
interaction. With curl, you can download or upload data using one of the supported protocols including
HTTP, HTTPS, SCP , SFTP , and FTP . curl provides a number of options allowing you to resume transfers,
limit the bandwidth, proxy support, user authentication, and much more.
Syntax : curl <ip address>
abhinavchebrolu@AbhinavChebrolu-VB:~$ curl gonav.in
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>GoNav | Home</title>
<meta name="description" content="" />
<meta name="keywords" content="" />
</head>
<frameset rows="100%,*" border="0">
<frame src="https://abhinavchebrolu.github.io/GoNav-LandingPage/" frameborder="0" />
</frameset>
</html>

abhinavchebrolu@AbhinavChebrolu-VB:~$ curl -O
https://www.google.com/logos/fnbx/top_ten/pacman_hero_1x.png

% Total % Received % Xferd Average Speed Time Time Time Current


Dload Upload Total Spent Left Speed
100 27722 100 27722 0 0 60927 0 --:--:-- --:--:-- --:--:-- 60927

Network and Communication : Lab FAT : 28-04-2022 58


CHEBROLU SAI PRASANNA ABHINAV – 20BCE2425

29. iftop
iftop is a network analyzing tool used by system administrators to view the bandwidth related stats. It
shows a quick overview of the networking activities on an interface. It stands from Interface TOP and the
top is derived from op command in Linux. It even acts as a diagnostics to diagnose which program is
causing the problem to the network.
Syntax : iftop
abhinavchebrolu@AbhinavChebrolu-VB:~$ iftop
interface: enp0s3
IP address is: 10.0.2.15
MAC address is: 08:00:27:0b:01:47
pcap_open_live(enp0s3): enp0s3: You don't have permission to capture on that device (socket: Operation not
permitted)

30. nmap
Nmap is Linux command-line tool for network exploration and security auditing. This tool is generally
used by hackers and cybersecurity enthusiasts and even by network and system administrators. It is
used for the following purposes: Real time information of a network; Detailed information of all the IPs
activated on your network; Number of ports open in a network; Provide the list of live hosts; Port, OS and
Host scanning.
Syntax : nmap <ip address>
abhinavchebrolu@AbhinavChebrolu-VB:~$ nmap gonav.in
Starting Nmap 7.80 ( https://nmap.org ) at 2022-01-23 18:32 IST
Nmap scan report for gonav.in (3.33.152.147)
Host is up (0.035s latency).
Other addresses for gonav.in (not scanned): 15.197.142.173
rDNS record for 3.33.152.147: a4ec4c6ea1c92e2e6.awsglobalaccelerator.com
Not shown: 998 filtered ports
PORT STATE SERVICE
53/tcp open domain
80/tcp open http

Nmap done: 1 IP address (1 host up) scanned in 6.03 seconds

Network and Communication : Lab FAT : 28-04-2022 59


CHEBROLU SAI PRASANNA ABHINAV – 20BCE2425

31. iperf
Iperf is an open source networking tool used to measure throughput or performance of a network. It can
be used to test TCP and UDP. Iperf can be used in Windows, Linux, and MAC etc operation system.
Syntax : iperf -s
abhinavchebrolu@AbhinavChebrolu-VB:~$ iperf -s
------------------------------------------------------------
Server listening on TCP port 5001
TCP window size: 128 KByte (default)
------------------------------------------------------------

Network and Communication : Lab FAT : 28-04-2022 60

You might also like