0% found this document useful (0 votes)
33 views64 pages

CN Files

The document describes configuring port security on a switch using Cisco Packet Tracer. Port security restricts access to switch interfaces by only allowing authorized devices with specific MAC addresses to use them. The key steps are: 1. Build a network topology with a switch connected to two PCs. 2. Configure the switch ports connected to the PCs (fa0/1 and fa0/2) as access ports and enable port security on them. 3. Define the allowed MAC addresses for each port so that only the connected PC's MAC can send traffic through that port. If an unauthorized device connects, the

Uploaded by

Aditya
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)
33 views64 pages

CN Files

The document describes configuring port security on a switch using Cisco Packet Tracer. Port security restricts access to switch interfaces by only allowing authorized devices with specific MAC addresses to use them. The key steps are: 1. Build a network topology with a switch connected to two PCs. 2. Configure the switch ports connected to the PCs (fa0/1 and fa0/2) as access ports and enable port security on them. 3. Define the allowed MAC addresses for each port so that only the connected PC's MAC can send traffic through that port. If an unauthorized device connects, the

Uploaded by

Aditya
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/ 64

 •–‹–—–‡‘ˆ‡ А‘Ž‘‰›ƒ†ƒƒ‰‡‡–

 ƒ‹†’—”ǡ‡ŽŠ‹ǦͳͳͲͲ͵͸
ȋˆˆ‹Žƒ–‡†‘ —”— ‘„‹†‹‰Š †”ƒ’”ƒ•–Šƒ‹˜‡”•‹–›ǡ
‡™‡ŽŠ‹Ȍ

/DERUDWRU\0DQXDO

&RPSXWHU1HWZRUNV

‡’–Computer Science And Engineering

Submitted To: —„‹––‡†›ǣ


Ms. †—Šƒ”ƒ   
CSE Departnment    ͷ
HMRITM   
,1'(;

S.NO. NAME OF EXPERIMENT PAGE DATE SIGNATURE


NO.

1. To create a simple network of a single router and


two end devices using Cisco Packet Tracer.

2. To create a simple network of Switches and Pcs


(Bus Topology) using Cisco Packet Tracer
3. Using Cisco Packet Tracer, configure port security
for switch interfaces.

4. Implement queue management algorithms that are


considered in network congestion

5. Implement the following unicast routing protocols.

6. To write a C Program on Dijkstra Algorithm for


Finding Minimum Distance Of Vertices from a
Given Source in a Graph.

7. To Write a C Program to implement Floyd


Warshall algorithm (All pairs shortest path).

8. Using C++/Java implement the following:

1.TCP ((CClient and server)) aand UDP ((CClient


and sserver))
2.FFTP ((CClient and sserver))
9. RSA is an asymmetric cryptography algorithm
which works on two keys-public key and private
key
1|Page

PRACTICAL--1

Aim::7RFUHDWHDVLPSOHQHWZRUNRIDVLQJOHURXWHUDQGWZRHQGGHYLFHVXVLQJ&LVFR
3DFNHW7UDFHU

Procedure::WesetupasimplenetworkconsistingofaRouter(1841)andtwoEnddevices
PC0,Laptop1.Itiscarriedoutinthefollowingmanner:
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

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.

Nitendra
Nitendra S
Singh
ingh
4|Page

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'.

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

Nitendra Singh
h
0011640532
0 011640532
5|Page

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.

Now steps to connect the second device (L 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'

Nitendra Singh
0011640532
6|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

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

Nitendra Singh
0011640532
7|Page

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.
8|Page

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

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

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

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.
10 | P a g

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.
11 | P a g

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.


12 | P a g

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

ч Check the message status (Successful)

ч Network is created (Bus Topology).


13 | P a g

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

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:

x Configure the port as an access port


x Enable port security
x Define which MAC addresses are allowed to send frames through this interface.
14 | P a g

x 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.
x Next,
x We’ll verify port security configurations on interfaces fa0/1 and fa0/2
x To verify if the switch has learnt the MAC address of PC1, you can use the command:

x show port-security interface fa0/1


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

x Try also pinging PC2 from PC1. Ping should be successful here since switch port
security is not violated.
x The case of Port Security Violation
15 | P a g

x Now connect a different PC to fa0/1 in place of PC1. See the effect of doing this:

x Notice that fa0/1 shuts down upon connecting the new PC, as indicated by the red
LED.
x 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.
x You can verify this further by using the command we used before: show port-
security interface fa0/1.

x Verify from above that port status is now Secure--shutdown upon violation of port
security.
x 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.
16 | P a g

How to Reset an interface that has been shut down due to Violation of Port Security::

x 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)
x Then run the following commands on the switch and test connectivity
from the authorized PC (PC1).
17 | P a g

Practical–
–0
04

Aim:: ,PSOHPHQW TXHXH PDQDJHPHQW DOJRULWKPV WKDW DUH FRQVLGHUHG LQ


QHWZRUNFRQJHVWLRQ

x Random Early Detection (R 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)

x 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.

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

x 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
18 | P a g

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.
19 | P a g

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.
20 | P a g

Practical – 05

Aim::,PSOHPHQWWKHIROORZLQJXQLFDVWURXWLQJSURWRFROV
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;
21 | P a g
pthread_mutex_t
LSDatabase::rlock;

list<RouterLSA> LSAManager::rlsaList;
list<NetworkLSA>
LSAManager::nlsaList;
22 | P a g

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_eth1;
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,NUL
L); 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,0x0
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
23 | P a g

#include "Timers.h"
#include "Sender.h"
#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>
24 | P a g
#include<string.h>
#include<sys/types.h>
#include<stdio.h>
#include<stdlib.h>
#include <sys/ioctl.h>
25 | P a g

#include <net/if.h>
#include
<arpa/inet.h>

class
Interface;
class
Neighbor;
class PacketManager
{
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 );
26 | P a g
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;
27 | P a g

static vector<RouterLSA> routerLSAList;


static vector<NetworkLSA>
networkLSAList; protected:
private:
};

OUTPUT
28 | P a g

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++)
{
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;
}
29 | P a g

}}
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
30 | P a g

Practical – 06

Aim::7RZULWHD&3URJUDPRQ'LMNVWUD$OJRULWKPIRU)LQGLQJ0LQLPXP'LVWDQFH
2I9HUWLFHVIURPD*LYHQ6RXUFHLQD*UDSK

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;
}
31 | P a g

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
//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++)
32 | P a g

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);
}while(j!=startnode);
}
}

OUTPUT
33 | P a g

Practical – 07

Aim::7R:ULWHD&3URJUDPWRLPSOHPHQW)OR\G:DUVKDOODOJRULWKP $OOSDLUVVKRUWHVWSDWK 
34 | P a g

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 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;
35 | P a g
k++) {
36 | P a g

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] == 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);
}
37 | P a g

Output::
38 | P a g

Practical – 08
Aim--8
8VLQJ&-DYDLPSOHPHQWWKHIIROORZLQJ
 TCP((Clientandserver))a
andUDP((Clientands
server))
 FTP((Clientands
server))

1. Implement TCP (C
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:
39 | P a g

TCP Server –
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

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
}

// Driver
function int
main()
42 | P a g

{
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);
}
43 | P a g

Output
44 | P a g

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;
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);
}
els printf("Socket successfully created..\n");
e
45 | P a g
bzero(&servaddr, sizeof(servaddr));

// assign IP, PORT


46 | P a g

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

// close the socket


close(sockfd);
}
47 | P a g

Output
48 | P a g

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

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.
49 | P a g

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;
50 | P a g
for (i = 0; i <= len; i++)
buf[i] = Cipher(buf[i]);
return 1;
}
51 | P a g

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,
52 | P a g

(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;
}
53 | P a g

Output
54 | P a g

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)
55 | P a g
return 1;
else printf("%c", ch);

}
56 | P a g

return 0;
}
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;
}
57 | P a g

Output
58 | P a g

Practical – 09
Definition--R6$LVDQDV\PPHWULFFU\SWRJUDSK\DOJRULWKPZKLFKZRUNVRQWZRNH\V
SXEOLFNH\DQGSULYDWHNH\

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
59 | P a g

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;
60 | P a g
else
61 | P a g

e++;
}
//private key
//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;
}
62 | P a g

Output

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy