0% found this document useful (0 votes)
31 views57 pages

Nitin CN File

Uploaded by

nitin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views57 pages

Nitin CN File

Uploaded by

nitin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 57

HMR INSTITUTE OF TECHNOLOGY AND MANAGEMENT

Hamidpur, Delhi-110036
(Affiliated to Guru Gobind Singh Indraprastha University, New
Delhi)

Submitted in partial fulfilment of the requirements


For the award of degree of
Bachelor of Technology
In
Computer Science and Engineering
2022-2026
COMPUTER NETWORKS
Lab File
Code: CIC-355
SUBMITTED TO: SUBMITTED BY:
Mr. Nidhi Nitin Jha
Assistant Professor 00196507223
CSE Department CSE 5-C
1|Page

PRACTICAL-1

Aim: To create a simple network of a single router and two end devices using Cisco Packet Tracer.

Procedure: We set up a simple network consisting of a Router (1841) and two End devices PC0,
Laptop1. It is carried out in the following manner:
A. Selecting the router and configuring the routers.
B. Selection of the End devices PC0 and Laptop1. Connecting them to the router using the Copper
cross-over connectors.

A. Selecting the router and configuring the routers.


1. Select router 1841 on to the center screen.

2. Select End Devices and drag on two computers on to the center screen.

3. For connecting the router and computers, we use crossover cable, Select copper crossover
cable.
2|Page

4. Click on Router0, select FastEthernet0/0 and connect the copper-crossover cable.

5. Click on the PC0 and select FastEthernet and connect the copper-crossover cable.
3|Page
4|Page

6. Select copper cross-over cable and Click on Router0, select FastEthernet0/1 and connect
the copper-crossover cable.

7. Click on the Laptop1 and select FastEthernet and connect the copper-crossover cable.
5|Page

Singh

Steps to activate the Router

8. Click on the router, press the Physical menu, we check whether the 'Green Light' on the
router switch, below the 'Zoom out'.
6|Page

B. Selection of the End devices PC0 and Laptop1. Connecting them to the router using the
Copper cross-over connectors.

9. Press the CLI button and you will see.


● type 'RETURN' (OR PRESS N and press enter
● you will get "Router" type 'enable' and
● you will get "Router#" and then type 'config terminal
10. You will see "Router (config)# " now type 'interface fastethernet0/0' at the command Prompt
(this is to access Ethernet0/0).
11. Type ‘ip address 192.168.1.1 255.255.255.0’.
12. Then type 'no shutdown.
7|Page

Now steps to connect the second device (Laptop1) to the router


13. Type Ctrl+Z.
14. Press Enter and You will see "Router>” then type 'enable'.
15. You will see "Router#" type 'config terminal'.
16. Now type 'interface fastethernet0/1' .
17. Type 'ip address 192.168.2.1 255.255.255.0'
18. Type 'no shutdown'
8|Page

Steps to Configure the PC0 and Laptop1:


This is to configure the gateway on each desktop computer. The gateway is the address we
assigned to the Ethernet port that the desktop is connected to. It will allow the computer to
interface with another network.
19. Click on PC0
20. Go to Config menu (the middle button) and click on it.
21. Go to Global (Press the button) we will see "settings" and press on it
22. Go to 'Gateway' field and type '192.168.1.1' and click on the 'Autoconfig' in the below
9|Page

23. Go to Fastethernet button on the left (which is the last button bellow the Global button) 24.
Go to the field "IP Address": Type '192.168.1.2' in the field and type '255.255.255.0 ' in the
subnet mask field
10 | P a g e

25. Go to Laptop1 press on it click 'Config' button


26. go to Global Settings and type '192.168.2.1' for the Gateway address field, and select on the
'Autoconfig' in the below.

27. Press the “FastEthernet” button on the left under the Global button.
28. Type '192.168.2.2 ' for the Ip Address and type '255.255.255.0' for the subnet mask field.
11 | P a g e

Steps to send the Packets


29. You will see "Envelope with a Plus symbol" on the top left bar menu.
30. Select the "packet" now click on PC0 (for sending a packet from PC0 to Laptop1). and then
press on Laptop1
12 | P a g e

31. We will see a "Successful" message in the message box on the lower right of the screen.

32. Select the packet from the right now click on Laptop1 and then on PC0 (for sending a packet
from Laptop1 to PC0).
13 | P a g e

33. Two packets have been successfully sent between the two end devices PC0 and Laptop1
through a router and thus a simple network has been created.
14 | P a g e

Practical - 02

Aim: To create a simple network of Switches and Pcs (Bus Topology) using
Cisco Packet Tracer.
Procedure: We set up a simple network consisting of 4 Switches and four End devices. It is carried
out in the following manner:
A. Select the switches and connect them using the Copper cross-over connectors.
B. Selection of the End devices. Connecting them to the respective Switch Device using the Copper
straight through connectors.
C. Configure IP address to the End devices.

A. Select the switches and connect them using the Copper cross-over connectors.
(i) Select Four Switches

(ii) Connect them using Copper Cross-over Connectors.

B. Selection of the End devices. Connecting them to the respective Switch Device using
the Copper straight through connectors.
(i) Select PCs as end devices.
15 | P a g e

ii) Connect the end devices with the corresponding Switches.

C. Configure IP address to the End devices (i)

Configure all of the PC’s with IP address.


16 | P a g e

Send Messages on the network, from one pc to another.

● Check the message status (Successful)

● Network is created (Bus Topology).


17 | P a g e

Practical -03

Aim: Using Cisco Packet Tracer, configure port security for switch interfaces.
Switch port Security is a network security feature that associates specific MAC addresses of
devices (such as PCs) with specific interfaces on a switch. This will enable you to restrict access
to a given switch interface so that only the authorized devices can use it. If an unauthorized device
is connected to the same port, you can define the action that the switch will take, such as discarding
the traffic, sending an alert, or shutting down the port.

1. Build the network topology:


18 | P a g e

PC1 connects to fa0/1 and PC2 to fa0/2 of the switch


2. Now configure switch port security on switch interfaces.
We’ll configure port security interfaces on fa0/1 and fa0/2. To do this, we’ll:

• Configure the port as an access port


• Enable port security
• Define which MAC addresses are allowed to send frames through this interface.
• The interface range command can save you tons of work in doing individual configurations
if you were configuring port security for many switch interfaces, say, 24 ports on a switch.
• Next,
• We’ll verify port security configurations on interfaces fa0/1 and fa0/2
• To verify if the switch has learnt the MAC address of PC1, you can use the command:
19 | P a g e

• show port-security interface fa0/1


• Verify that the switch has learnt the MAC address of PC1.
• You may also use the command: show port-security address.

• Try also pinging PC2 from PC1. Ping should be successful here since switch port security
is not violated.
• The case of Port Security Violation

• Now connect a different PC to fa0/1 in place of PC1. See the effect of doing this:
20 | P a g e

• Notice that fa0/1 shuts down upon connecting the new PC, as indicated by the red LED.
• This is because the switch had already associated fa0/1 with the MAC address of PC1 and
the maximum number of MAC addresses that we defined for this port is 1 So attaching the
new PC to fa0/1 violates the port security rules that we set and as a result, the interface
shuts down.
• You can verify this further by using the command we used before: show port-security
interface fa0/1.

• Verify from above that port status is now Secure-shutdown upon violation of port
security.
• Further, a ping from the New PC to PC2 will definitely fail because the switch cannot
forward a frame via an interface that is shut down.
How to Reset an interface that has been shut down due to Violation of Port Security:
21 | P a g e

• One of the options on the table is to manually restart the shutdown interface(fa0/1 in our
case here). Unplug the cable from the unauthorized PC(new PC) and plug it back to the
authorized PC(PC1)
• Then run the following commands on the switch and test connectivity from the authorized
PC (PC1).

Practical – 04

Aim: Implement queue management algorithms that are considered in network


congestion

Random Early Detection (RED)


RED was proposed by Floyd and Van Jacobson in the early 1990s to address network congestion
in a responsive rather than reactive manner. It is a congestion avoidance mechanism. The main
goal is to provide congestion avoidance by controlling the average queue size. Other goals are the
avoidance of global synchronization* and introduce fairness to reduce the bias against bursty
traffic.
TCP global synchronization in computer networks can happen to TCP/IP flow during periods of
congestion because each sender will reduce and then increase their transmission rate at the same
time when packet loss occurs)
22 | P a g e

What Random and Early means


1. RANDOM
In order to avoid biases against bursty traffic and global synchronization, RED uses randomization
in choosing which arriving packets to drop or mark.
2. EARLY
The “early” part of the RED acronym suggests that the router drops the packet earlier than it would
have to, so as to notify the source that it should decrease its congestion window sooner than it
would normally.

HOW IT WORKS
Red mechanism detects incipient congestion and decides which connections to notify of congestion
at the gateway.

RED ALGORITHM PROCESS


RED aims to control the average queue size by informing the end host to slow down the
transmission of packets. It monitors the average queue size and drops or marks packets based on
statistical probabilities

The following process is performed:


1. We have an incoming packet
2. The average queue length is computed
3. If avr<min length threshold then the packet is placed in the queue
4. If min<avr<max queen this then check dropping probability (Pa)
1. If high probability => packet is dropped
2. If low probability => packed placed in the queue
5. If avr>max =>packet is droppe
23 | P a g e

The rate of packet drop increases linearly as the average queue size increases until the average
queue size reaches the maximum threshold. The packet drop probability is based on the minimum
threshold, maximum threshold, and mark probability denominator.
24 | P a g e

When the average queue depth is above the minimum threshold, RED starts dropping packets. The
rate of packet drop increases linearly as the average queue size increases until the average queue
size reaches the maximum threshold.
The min three should be high enough to maximize link usage. If the min three is too low, then
many packet be dropped unnecessarily.
Also, the difference between min and max three should be enough in order to avoid global
synchronization. If the difference is not enough, then senders will back-off almost at the same time.
With RED we avoid TCP global synchronization. RED gateways avoid global synchronization by
marking packets at as low a rate as possible.
25 | P a g e

Practical – 05

Aim: Implement the following unicast routing protocols.


i. Open Shorting Path First (OSPF)

Program Code

#include <iostream>
#include <pthread.h>
#include "Timer.h"
#include <unistd.h>
#include "Config.h"
#include "PacketManager.h"
#include "Interface.h"
#include "InterfaceEventState.h"
#include "LSDatabase.h"
#include "LSAManager.h" #include
"Common.h"

using namespace std;

/* beign init of static memebers */ uint32_t


Config::routerId = ntohl(inet_addr("192.168.2.101"));
vector<RouterLSA> LSDatabase::routerLSAList;
vector<NetworkLSA> LSDatabase::networkLSAList;
pthread_mutex_t LSAManager::rlock; pthread_mutex_t
LSAManager::nlock;
pthread_mutex_t LSDatabase::rlock;
26 | P a g e

list<RouterLSA> LSAManager::rlsaList; list<NetworkLSA>


LSAManager::nlsaList; vector<Interface*> Config::inters;
/* end init of static memebers */ int
main()

{
pthread_mutex_init(&LSAManager::rlock,NULL)
;
pthread_mutex_init(&LSAManager::nlock,NULL
);
pthread_mutex_init(&LSDatabase::rlock,NULL);
pthread_t recvThread; pthread_t helloSendThread;
pthread_t helloRecvThread; pthread_t lsathread;
Interface inter_eth1;
inter_eth1.ip = ntohl(inet_addr("192.168.2.101"));
Config::inters.push_back(&inter_eth1);
//inter_eth1.dr=ntohl(inet_addr("192.168.2.1"));
// inter_eth1.mask = EventArgs
arg;
arg.eventId = IT_EVT_INTERFACEUP; inter_eth1.invokeEvent(PACKET_RECV,arg);
pthread_create(&helloRecvThread,NULL,PacketManager::recvHelloPacket,&inter_eth
1; pthread_create(&helloSendThread,NULL,PacketManager::sendHello,&inter_eth1);
pthread_create(&lsathread,NULL,LSAManager::lsaGenerate,NULL);
//pthread_create(&recvThread,NULL,PacketManager::recvPacket,&inter_eth1);
pthread_join(helloRecvThread,NULL); pthread_join(helloSendThread,NULL);
pthread_join(recvThread,NULL);
return 0;
} int main2()
{ uint8_t
data[34]={0x02,0x01,0xc0,0xa8,0x2,0x64,0xc0,0xa8,0x02,0x64,0x80,0x00,0x00,0x11,
0
x00,0x00,0x00,0x24,0x00,0x00,0x00,0x01,0xc0,0xa8,0x02,0x00,0xff,0xff,0xff,0x00,0
x0 3,0x00, 0x00,0x01};
//uint8_t
data[32]={0x02,0x01,0xc0,0xa8,0x2,0x64,0xc0,0xa8,0x02,0x64,0x80,0x00,0x00,0x11,0
x00,0x24,0x00,0x00,0x00,0x01,0xc0,0xa8,0x02,0x00,0xff,0xff,0xff,0x00,0x03,0x00,0x0
0,0x01}; uint16_t value =
Common::create_osi_cksum(data,14,34);

printf("%x\n",value);
}
Timer.h
#include "Timers.h" #include
"Sender.h"
27 | P a g e

#include "Interface.h"
#include "EventArgs.h"
#include <unistd.h>
#include "InterfaceEventState.h"

void* Timers::waitTimer(void* inter){ Interface*


interface = (Interface*)inter;

sleep(40); EventArgs args; args.eventId =


IT_EVT_WAITTIMER; interface-
>invokeEvent(WAIT_TIMER,args);
}

Config.h
#ifndef CONFIG_H
#define CONFIG_H
#include <stdint.h>
#include <vector>

using namespace std; class


Interface; class Config { public:
static uint32_t routerId; static
vector<Interface*> inters; };

#endif // CONFIG_H

Packetmanager.h
#ifndef PACKETMANAGER_H
#define PACKETMANAGER_H
#include "Packets.h"
#include<sys/socket.h>
#include<netinet/in.h>
#include<netinet/ip.h>
#include<strings.h>
#include<string.h>
#include<sys/types.h>
#include<stdio.h>
#include<stdlib.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <arpa/inet.h>

class Interface; class


Neighbor; class
PacketManager
28 | P a g e

{ public:
PacketManager();
static void* recvPacket(void* interface);
//static void* sendPacket(void*
interface); static void* sendHello(void*
inter); static void* sendDDPackets(void
*nbr);
static void sendPacket(const
char*,int,int,uint32_t,Interface*); static void*
recvHelloPacket(void *inter); static void
*sendEmptyDDPacets(void *nbr); static void
*sendLSReq(void* nbr); protected:
private:
};
#endif // PACKETMANAGER_H
lSdatabase.h
#ifndef LSDATABASE_H
#define LSDATABASE_H
#include <vector>
#include <stdlib.h>
#include "Packets.h"
#include
<pthread.h> using
namespace std; class
LSDatabase
{ public:
LSDatabase(); static RouterLSA *getRouterLSAById(uint32_t linkId,uint32_t
adr_id); static NetworkLSA *getNetworkLSAById(uint32_t linkId,uint32_t
adr_id);
static bool remove(uint32_t linkId, uint32_t adr_id, int type);
static void insertRouterLSA(RouterLSA lsa); static void
insertNetworkLSA(NetworkLSA lsa); static RouterLSA
*getRouterLSAByAdrId(uint32_t adr_id); static NetworkLSA
*getNetworkLSAByAdrId(uint32_t adr_id); static void
removeByAdrId( uint32_t ad_router, int type ); static RouterLSA
*getRouterLSAByLinkStateId(uint32_t linkId); static NetworkLSA *
getNetworkLSAByLinkStateId( uint32_t linkId ); static
pthread_mutex_t rlock; static pthread_mutex_t nlock; static
pthread_mutex_t slock;
static vector<RouterLSA> routerLSAList;
static vector<NetworkLSA> networkLSAList;
protected: private:
};
29 | P a g e

OUTPUT

ii. Border Gateway Protocol (BGP)

#include <stdio.h>
#include<conio.h>
int main() { int n;
int i,j,k; int a[10][10],b[10][10];
printf("\n Enter the number of nodes:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
30 | P a g e

for(j=0;j<n;j++)
{
printf("\n Enter the distance between the host %d - %d:",i+1,j+1); scanf("%d",&a[i][j]);
}}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("%d\t",a[i][j]);
} printf("\n");
}
for(k=0;k<n;k++)
{
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(a[i][j]>a[i][k]+a[k][j])
{
a[i][j]=a[i][k]+a[k][j];
}}}}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
b[i][j]=a[i][j]
; if(i==j) {
b[i][j]=0;
}
}}
printf("\n The output
matrix:\n"); for(i=0;i<n;i++) {
for(j=0;j<n;j++) {
printf("%d\t",b[i][j]);
}
printf("\n")
; } getch();
}

OUTPUT
31 | P a g e

Practical – 06

Aim: To write a C Program on Dijkstra Algorithm for Finding Minimum Distance Of


Vertices from a Given Source in a Graph.
32 | P a g e

Program Code

#include<stdio.h>
#include<conio.h>
#define INFINITY 9999 #define
MAX 10
void dijkstra(int G[MAX][MAX],int n,int startnode); int
main()
{
int G[MAX][MAX],i,j,n,u;
printf("Enter no. of vertices:");
scanf("%d",&n);
printf("\nEnter the adjacency
matrix:\n"); for(i=0;i<n;i++)
for(j=0;j<n;j++) scanf("%d",&G[i][j]);
printf("\nEnter the starting node:");
scanf("%d",&u);
dijkstra(G,n,u);
return 0;
}
void dijkstra(int G[MAX][MAX],int n,int startnode)
{
int cost[MAX][MAX],distance[MAX],pred[MAX];
int visited[MAX],count,mindistance,nextnode,i,j;
//pred[] stores the predecessor of each node
//count gives the number of nodes seen so far
33 | P a g e

//create the cost matrix


for(i=0;i<n;i++)
for(j=0;j<n;j++)
if(G[i][j]==0)
cost[i][j]=INFINITY;
else
cost[i][j]=G[i][j];
//initialize pred[],distance[] and visited[]
for(i=0;i<n;i++)
{
distance[i]=cost[startnode][i]
; pred[i]=startnode;
visited[i]=0; }
distance[startnode]=0;
visited[startnode]=1;
count=1;
while(count<n-1)
{
mindistance=INFINITY;
//nextnode gives the node at minimum distance for(i=0;i<n;i++)
if(distance[i]<mindistance&&!visited[i])
{
mindistance=distance[i];
nextnode=i;
}
//check if a better path exists through
nextnode visited[nextnode]=1;
for(i=0;i<n;i++)
if(!visited[i])
if(mindistance+cost[nextnode][i]<distance[i])
{
distance[i]=mindistance+cost[nextnode][i];
pred[i]=nextnode;
} count++;
}
//print the path and distance of each node for(i=0;i<n;i++)

if(i!=startnode)
{
printf("\nDistance of node%d=%d",i,distance[i]);
printf("\nPath=%d",i);
j=i; do { j=pred[j];
printf("<-%d",j);
34 | P a g e

}while(j!=startnode)
;
}
}

OUTPUT

Practical – 07

Aim: To Write a C Program to implement Floyd Warshall algorithm (All pairs shortest path).
35 | P a g e

Program Code

#include <stdio.h>
// defining the number of vertices
#define nV 4 #define INF 999 void
printMatrix(int matrix[][nV]); //
Implementing floyd warshall algorithm
36 | P a g e

void floydWarshall(int graph[][nV]) { int


matrix[nV][nV], i, j, k; for (i = 0; i < nV;
i++) for (j = 0; j < nV; j++) matrix[i][j] =
graph[i][j]; printf("Input matrix: \n"); for
(i = 0; i < nV; i++)
{ for (j = 0; j < nV;
j++)
{
if(matrix[i][j]==999)
{ printf(" INF
"); } else {
printf(" %d ",matrix[i][j]);
}
}printf("\n");
}
// Adding vertices individually for
(k = 0; k < nV; k++) {

for (i = 0; i < nV; i++) { for (j = 0; j < nV; j++) { if


(matrix[i][k] + matrix[k][j] < matrix[i][j])
matrix[i][j] = matrix[i][k] + matrix[k][j];
}
}}
printMatrix(matrix)
;
} void printMatrix(int matrix[][nV]) { printf("\nshortest
path between each pair of vertices: \n"); for (int i = 0; i <
nV; i++) { for (int j = 0; j < nV; j++) { if (matrix[i][j] ==
37 | P a g e

INF) printf("%4s", "INF"); else printf("%4d",


matrix[i][j]);
}
printf("\n");
} } int
main() {
int graph[nV][nV] = {{0, 3, INF, 5},
{2, 0, INF, 4},
{INF, 1, 0, INF}, {INF,
INF, 2, 0}};
floydWarshall(graph);
}
Output:
38 | P a g e

Practical – 08
Aim - Using C++/Java implement the following:
1. TCP (Client and server) and UDP (Client and server)
2. FTP (Client and server)

1. Implement TCP (Clint and server) program in C++.

If we are creating a connection between client and server using TCP then it has few functionality
like, TCP is suited for applications that require high reliability, and transmission time is relatively
less critical. It is used by other protocols like HTTP, HTTPs, FTP, SMTP, Telnet. TCP rearranges
data packets in the order specified. There is absolute guarantee that the data transferred remains
intact and arrives in the same order in which it was sent. TCP does Flow Control and requires three
packets to set up a socket connection, before any user data can be sent. TCP handles reliability and
congestion control. It also does error checking and error recovery. Erroneous packets are
retransmitted from the source to the destination. The entire process can be broken down into
following steps:

TCP Server –
39 | P a g e

1. Using create (), Create TCP socket.


2. Using bind (), Bind the socket to server address.
3. using listen(), put the server socket in a passive mode, where it waits for the client to approach
the server to make a connection
4. Using accept (), At this point, connection is established between client and server, and they are
ready to transfer data.
5. Go back to Step 3.

TCP Client – 1. Create


TCP socket.
2. Connect newly created client socket to server.
40 | P a g e

TCP Server Side Program

#include <stdio.h>
#include <netdb.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#define MAX 80
#define PORT 8080
#define SA struct sockaddr

// Function designed for chat between client and server. void


func(int sockfd)
{
char buff[MAX];
int n;
// infinite loop for chat for
(;;) {
bzero(buff, MAX);

// read the message from client and copy it in buffer read(sockfd,


buff, sizeof(buff));
// print buffer which contains the client contents
printf("From client: %s\t To client : ", buff);
bzero(buff, MAX);
n = 0;
// copy server message in the buffer while
((buff[n++] = getchar()) != '\n')
;

// and send that buffer to client write(sockfd,


buff, sizeof(buff));

// if msg contains "Exit" then server exit and chat ended.


if (strncmp("exit", buff, 4) == 0) {
printf("Server Exit...\n");
break;
}
}
}
41 | P a g e

// Driver function int


main()
{ int sockfd, connfd, len;
struct sockaddr_in servaddr, cli;

// socket create and verification


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));

// assign IP, PORT servaddr.sin_family = AF_INET;


servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(PORT);

// Binding newly created socket to given IP and verification


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);
// Accept the data packet from client and verification connfd
= accept(sockfd, (SA*)&cli, &len);
if (connfd < 0) { printf("server acccept
failed...\n"); exit(0);
} else printf("server acccept the client...\n");
func(connfd);
close(sockfd);
}

Output
42 | P a g e

TCP Clint Side Program


#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#define MAX 80
#define PORT 8080
#define SA struct sockaddr void
func(int sockfd)
{
char buff[MAX];
int n;
for (;;) { bzero(buff,
sizeof(buff)); printf("Enter
the string : "); n = 0;
43 | P a g e

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

int main()
{
int sockfd, connfd; struct
sockaddr_in servaddr, cli;

// socket create and varification


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));

// assign IP, PORT

servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = inet_addr("127.0.0.1"); servaddr.sin_port
= htons(PORT);

// connect the client socket to server socket


if (connect(sockfd, (SA*)&servaddr, sizeof(servaddr)) != 0)
{ printf("connection with the server failed...\n");
exit(0);
} else printf("connected to the
server..\n");

// function for chat


func(sockfd);
44 | P a g e

// close the socket close(sockfd);


}
45 | P a g e

Output

C program for file Transfer using UDP.

Data can be transferred between two computers using Socket programming in C.


Similarly, files can easily be sent using UDP protocol and a simple client/server.
Security: Handled by encryption. Protocol:
UDP
46 | P a g e

Algorithm:
1. The server starts and waits for filename.
2. The client sends a filename.
3. The server receives filename.
If file is present, server starts reading file and continues to send a buffer filled with file contents
encrypted until file-end is reached.
4. End is marked by EOF.
5. File is received as buffers until EOF is received. Then it is decrypted.
6. If Not present, a file not found is sent.
47 | P a g e

Server Side Program

// server code for UDP socket programming


#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h> #include
<string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>

#define IP_PROTOCOL 0
#define PORT_NO 15050
#define NET_BUF_SIZE 32
#define cipherKey 'S'
#define sendrecvflag 0
#define nofile "File Not Found!"

// function to clear buffer void


clearBuf(char* b)
{ int i;
for (i = 0; i < NET_BUF_SIZE; i++)
b[i] = '\0';
}

// function to encrypt char


Cipher(char ch)
{ return ch ^ cipherKey;
}

// function sending file


int sendFile(FILE* fp, char* buf, int s)
{ int i, len;
if (fp == NULL) { strcpy(buf, nofile);
len = strlen(nofile); buf[len] =
EOF; for (i = 0; i <= len; i++)
buf[i] = Cipher(buf[i]);
return 1;
}
48 | P a g e

char ch, ch2; for (i = 0; i


< s; i++) { ch = fgetc(fp);
ch2 = Cipher(ch); buf[i]
= ch2;
if (ch == EOF) return
1;
} return
0;
}

// driver code int


main()
{ int sockfd, nBytes; struct sockaddr_in addr_con; int
addrlen = sizeof(addr_con);
addr_con.sin_family = AF_INET;
addr_con.sin_port = htons(PORT_NO);
addr_con.sin_addr.s_addr = INADDR_ANY;
char net_buf[NET_BUF_SIZE];
FILE* fp;

// socket()
sockfd = socket(AF_INET, SOCK_DGRAM, IP_PROTOCOL);

if (sockfd < 0) printf("\nfile descriptor not


received!!\n");
else printf("\nfile descriptor %d received\n", sockfd);

// bind()
if (bind(sockfd, (struct sockaddr*)&addr_con, sizeof(addr_con)) == 0)
printf("\nSuccessfully binded!\n");
else printf("\nBinding Failed!\n");

while (1) { printf("\nWaiting for file


name...\n");

// receive file name clearBuf(net_buf);

nBytes = recvfrom(sockfd, net_buf,


NET_BUF_SIZE, sendrecvflag,
49 | P a g e

(struct sockaddr*)&addr_con, &addrlen);

fp = fopen(net_buf, "r");
printf("\nFile Name Received: %s\n", net_buf);
if (fp == NULL) printf("\nFile open failed!\n");
else printf("\nFile Successfully opened!\n");
while (1) {

// process
if (sendFile(fp, net_buf, NET_BUF_SIZE)) {
sendto(sockfd, net_buf, NET_BUF_SIZE,
sendrecvflag,
(struct sockaddr*)&addr_con, addrlen); break;
}

// send
sendto(sockfd, net_buf, NET_BUF_SIZE, sendrecvflag,
(struct sockaddr*)&addr_con, addrlen); clearBuf(net_buf);
} if (fp !=
NULL)
fclose(fp);
} return
0;
}

Output
50 | P a g e
51 | P a g e

Program for Clint

// client code for UDP socket programming


#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h> #include
<string.h>
#include <sys/socket.h>
#include <sys/types.h> #include
<unistd.h>

#define IP_PROTOCOL 0
#define IP_ADDRESS "127.0.0.1" // localhost
#define PORT_NO 15050
#define NET_BUF_SIZE 32
#define cipherKey 'S'
#define sendrecvflag 0

// function to clear buffer void


clearBuf(char* b)
{ int i;
for (i = 0; i < NET_BUF_SIZE; i++)
b[i] = '\0';
}

// function for decryption char


Cipher(char ch)
{ return ch ^ cipherKey;
}

// function to receive file int


recvFile(char* buf, int s)
{ int i; char ch; for (i = 0; i < s;
i++) { ch = buf[i]; ch =
Cipher(ch); if (ch ==
EOF) return 1;
else
printf("%c", ch);
}

return 0;
52 | P a g e

} int
main()
{ int sockfd, nBytes; struct sockaddr_in addr_con; int addrlen
= sizeof(addr_con); addr_con.sin_family = AF_INET;
addr_con.sin_port = htons(PORT_NO);
addr_con.sin_addr.s_addr = inet_addr(IP_ADDRESS);
char net_buf[NET_BUF_SIZE];
FILE* fp; //
socket()
sockfd = socket(AF_INET, SOCK_DGRAM,
IP_PROTOCOL);

if (sockfd < 0) printf("\nfile descriptor not


received!!\n"); else printf("\nfile descriptor %d
received\n", sockfd);

while (1) { printf("\nPlease enter file name to


receive:\n"); scanf("%s", net_buf);
sendto(sockfd, net_buf, NET_BUF_SIZE,
sendrecvflag, (struct
sockaddr*)&addr_con, addrlen);
printf("\n---------Data Received -------- \n");

while (1) { // receive


clearBuf(net_buf)
;
nBytes = recvfrom(sockfd, net_buf, NET_BUF_SIZE, sendrecvflag,
(struct sockaddr*)&addr_con, &addrlen);

// process
if (recvFile(net_buf, NET_BUF_SIZE)) { break;
}
}
printf("\n \n");
} return
0;
}
Output
53 | P a g e

Practical – 09
Definition - RSA is an asymmetric cryptography algorithm which works on two keys-public key
and private key.

Algorithm –
Begin
1. Choose two prime numbers p and q.
2. Compute n = p*q.
3. Calculate phi = (p-1) * (q-1).
4. Choose an integer e such that 1 < e < phi(n) and gcd(e, phi(n)) = 1; i.e., e and phi(n) are
coprime.
5. Calculate d as d ≡ e−1 (mod phi(n)); here, d is the modular multiplicative inverse of e
modulo phi(n).
6. For encryption, c = me mod n, where m = original message.
7. For decryption, m = c d mod n.
End
54 | P a g e

Program Code
#include<iostream>
#include<math.h>
using namespace std;
// find gcd int
gcd(int a, int b) { int
t;
while(1) {
t= a%b;
if(t==0)
return b;
a = b;
b= t;
} } int
main() {
//2 random prime numbers
double p = 13; double q =
11; double
n=p*q;//calculate n
double track;
double phi= (p-1)*(q-1);//calculate phi
//public key
//e stands for encrypt double
e=7;
//for checking that 1 < e < phi(n) and gcd(e, phi(n)) = 1; i.e., e and phi(n) are coprime.
while(e<phi) { track = gcd(e,phi); if(track==1)
break;
else e++;

}
//private key
55 | P a g e

//d stands for decrypt


//choosing d such that it satisfies d*e = 1 mod phi
double d1=1/e; double d=fmod(d1,phi); double
message = 9; double c = pow(message,e);
//encrypt the message double m = pow(c,d);
c=fmod(c,n); m=fmod(m,n); cout<<"Original
Message = "<<message; cout<<"\n"<<"p = "<<p;
cout<<"\n"<<"q = "<<q; cout<<"\n"<<"n = pq =
"<<n; cout<<"\n"<<"phi = "<<phi;
cout<<"\n"<<"e = "<<e; cout<<"\n"<<"d = "<<d;
cout<<"\n"<<"Encrypted message = "<<c;
cout<<"\n"<<"Decrypted message = "<<m; return
0;
}
Output
56 | P a g e

You might also like