Anda di halaman 1dari 71

Networks Laboratory 2009-10

PART-A

1
Networks Laboratory 2009-10

Introduction to NCTUns
NCTUns is a network simulator and emulator. It provides many unique advantages over
traditional network simulators and emulators. NCTUns is open-source and runs on Linux. It
can simulate many different types of networks. It has many high-quality journal and
conference papers supporting its simulation methodology, design, and implementation.

Network simulators implemented in software are valuable tools for researchers to develop,
test, and diagnose network protocols. Simulation is economical because it can carry out
experiments without the actual hardware. It is flexible because it can, for example, simulate
a link with any bandwidth and propagation delay. Simulation results are easier to analyze
than experimental results because important information at critical points can be easily
logged to help researchers diagnose network protocols.

NCTUns can be used as an emulator. An external host in the real world can exchange
packets (e.g., set up a TCP connection) with nodes (e.g., host, router, or mobile station) in a
network simulated by NCTUns. Two external hosts in the real world can also exchange
their packets via a network simulated by NCTUns. This feature is very useful as the
function and performance of real-world devices can be tested under various simulated
network conditions. It directly uses the real-life Linux’s TCP/IP protocol stack to generate
high-fidelity simulation results. It can use any real-life existing or to-be-developed UNIX
application program as a traffic generator program without any modification. Any real-life
program can be run on a simulated network to generate network traffic. This enables a
researcher to test the functionality and performance of a distributed application or system
under various network conditions. Another important advantage of this feature is that
application programs developed during simulation studies can be directly used on real-
world UNIX machines and deployed in the real world after simulation studies are finished.
This eliminates the time and effort required to port a simulation prototype to a real-world
implementation if traditional network simulators are used. It can use any real-life UNIX
network configuration and monitoring tools.

2
Networks Laboratory 2009-10

In NCTUns, the setup and usage of a simulated network and application programs are
exactly the same as those used in real-world IP networks. For example, each layer-3
interface has an IP address assigned to it and application programs directly use these IP
addresses to communicate with each other. For this reason, any person who is familiar with
real-world IP networks can easily learn and operate NCTUns in a few minutes. For the
same reason, NCTUns can be used as an educational tool to teach students how to
configure and operate a real-world network. It can simulate fixed Internet, Wireless LANs,
mobile ad hoc (sensor) networks, GPRS networks, and optical networks.

It can simulate various networking devices. For example, Ethernet hubs, switches, routers,
hosts, IEEE 802.11 (b) wireless stations and access points, WAN (for purposely
delaying/dropping/reordering packets), Wall (wireless signal obstacle), GPRS base station,
GPRS phone, GPRS GGSN, GPRS SGSN, optical circuit switch, optical burst switch, QoS
DiffServ interior and boundary routers, etc.

It can simulate various protocols. For example, IEEE 802.3 CSMA/CD MAC, IEEE 802.11
(b) CSMA/CA MAC, learning bridge protocol, spanning tree protocol, IP, Mobile IP,
Diffserv (QoS), RIP, OSPF, UDP, TCP, RTP/RTCP/ SDP, HTTP, FTP, Telnet, etc.

It provides a highly-integrated and professional GUI environment. This GUI can help a user
(1) draw network topologies, (2) configure the protocol modules used inside a node, (3)
specify the moving paths of mobile nodes, (4) plot network performance graphs, (5) play
back the animation of a logged packet transfer trace, etc. All these operations can be easily
and intuitively done with the GUI.

NCTUns uses a simple but effective syntax to describe the settings and configurations of a
simulation job. These descriptions are generated by the GUI and stored in a suite of files.
Normally the GUI will automatically transfer these files to the simulation engine for
execution.

Snap shots of operation modes of NCTUns

3
Networks Laboratory 2009-10

1. Draw Topology
An environment to specify a network topology

Tool Bar

2. Edit Property
An environment to configure which modules to be used inside a node
4
Networks Laboratory 2009-10

Host: Dialog box

3. Run Simulation
An interface to control the execution of simulations

5
Networks Laboratory 2009-10

4. Playback
A player to play back logged packet transfer trace Playback

Setting up the environment

6
Networks Laboratory 2009-10

A user using the NCTUns in single machine needs to do the following steps before he/she
starts the GUI program:

1. Start up the dispatcher on terminal 1.


Path: /usr/local/nctuns/bin/dispatcher

2. Start up the coordinator on terminal 2.


Path: /usr/local/nctuns/bin/coordinator

3. Start up the nctunsclient on terminal 3.


Path: /usr/local/nctuns/bin/nctunsclient

After the above steps are followed, the user is presented with the working window as
shown below:

1. Simulate a three nodes point-to-point network with duplex links between them.
Set the queue size and vary the bandwidth and find the number of packers
dropped.

7
Networks Laboratory 2009-10

Step 1: Create the topology as specified in the question in the draw mode of the simulator.

Step 2: Go to edit mode and save the topology.

Step 3: Set up a UDP connection between node 1 and node 2 using the following
commands:
stg [-u payload size duration] [Hostaddress]
rtg [-u] [-w log]

Step 4: Select node editor -> MAC -> log statistics and select Number of Drop packets,
Number of Collisions, Throughput of incoming packets and Throughput of outgoing
packets. Select FIFO and set the queue size as 50.

Step 5: To view the results, go to the filename.results folder.

Example and Result:

Command used: stg –u 1024 100 1.0.1.2


rtg –u –w log1

By setting the bandwidth as 10 Mbps on both the links and queue size as 50 we obtain the
following results:

Output throughput:1177
Input throughput: 1177
Collision and drop: 0

By changing bandwidth to 9 Mbps in the destination link, we obtain the following results:

Output throughput:1177
Input throughput: 0
Collision and drop: 1100

The results of the experiments vary from simulation to simulation.

2. Simulate a four node point – to – point network and connect the links as
follows : n0 –n2, n1 – n2 and n2 – n3. Apply TCP agent between n0 – n3 and
UDP n1 – n3. Apply relevant applications over TCP and UDP agents changing the
parameter and determine the number of packets sent by TCP / UDP.

8
Networks Laboratory 2009-10

Step 1: Create the topology as specified in the question in the draw mode of the simulator.

Step 2: Go to edit mode and save the topology.

Step 3: Set up a TCP connection between node 1 and node 3 using the following
commands:
stcp [-p port] –l writesize] hostIPaddr
rtcp [-p port] [-l readsize]

Step 4: Set up a UDP connection between node 2 and node 3 using the following
commands:
stg [-u payload size duration] [Hostaddress]
rtg [-u] [-w log]

Step 5: Select node editor -> MAC -> log statistics and select Throughput of outgoing
packets for both TCP and UDP links. Select FIFO and set the queue size as 50.

Step 6: To view the results, go to the filename.results folder.

Example and Result:

Command used: stg –u 1024 100 1.0.1.3


rtg –u –w log1

stcp –p 7000 –l 1024 1.0.1.3


rtcp –p 7000 –l 1024

By setting the bandwidth as 100 Mbps on the TCP link and queue size as 50 we obtain the
following results:

Average no. of TCP packets sent: varying (348 to 1100)


Average no. of UDP packets sent: 1180

The result varies based on the bandwidth.

3. Simulate the different types of internet traffic such as FTP and TELNET over
a network and analyze the throughout.

To setup a FTP connection:

9
Networks Laboratory 2009-10

Step 1: Create the topology for four nodes; connect these nodes to a hub.

Step 2: Go to edit mode and setup FTP traffic between node 1 and node 4 using the port
number 21.

Step 3: Set up a TCP connection between the nodes using the following commands:
stcp [-p port] –l writesize] hostIPaddr
rtcp [-p port] [-l readsize]

Step 4: Select node editor -> MAC -> log statistics and select Throughput of incoming
packets and Throughput of outgoing packets. Select FIFO and set the queue size as 50.

Step 5: To view the results, go to the filename.results folder.

To setup a TELNET connection:

Step 1: Create the topology for four nodes; connect these nodes to a hub.

Step 2: Go to edit mode and setup TELNET traffic between node 1 and node 4 using the
port number 23.

Step 3: Set up a TCP connection between the nodes using the following commands:
stcp [-p port] –l writesize] hostIPaddr
rtcp [-p port] [-l readsize]

Step 4: Select node editor -> MAC -> log statistics and select Throughput of incoming
packets and Throughput of outgoing packets. Select FIFO and set the queue size as 50.

Step 5: To view the results, go to the filename.results folder.

Example and Result:

For FTP:

Command used: stcp –p 21 –l 1024 1.0.1.6


rtcp –p 21 –l 1024

10
Networks Laboratory 2009-10

Output throughput: 680 - 1100


Input throughput: 680 - 1100

For TELNET:

Command used: stcp –p 23 –l 1024 1.0.1.6


rtcp –p 23 –l 1024

Output throughput: 500 - 1100


Input throughput: 500 - 1100

4. Simulate the transmission of ping messages over a network topology consisting


of 6 nodes and find the number of packers dropped due to congestion.

Step 1: Click on the subnet icon on the toolbar and then click on the screen of the working
window.

Step 2: Select the required number of hosts and a suitable radius between the host and the
switch.

11
Networks Laboratory 2009-10

Step 3: In the edit mode, get the IP address of one of the hosts say, host 1 and then for the
other host say, host 2 set number of drop packet and collisions statistics.

Step 4: Now run the simulation.

Step 5: Now click on any one of the hosts and click on command console and ping the
destination node.

Note: The number of drop packets is obtained only when the traffic is more in the network.

Example and Result:

No need to setup any commands on the node editor.


During Run mode open command console and ping 1.0.1.6.

5. Simulate an Ethernet LAN using N nodes (6-10). Change error rate and data
rate and compare throughput.

Step 1: Connect one set of hosts with a hub and another set of hosts also through a hub and
connect these two hubs through a switch. This forms an Ethernet LAN.

Step 2: Set up a TCP connection between a host on one hub and host on another hub using
the following commands:
stcp [-p port] –l writesize] hostIPaddr
rtcp [-p port] [-l readsize]

12
Networks Laboratory 2009-10

Step 3: Set up the error rate, data rate in the physical layer, input and output throughput in
the MAC layer.

Step 4: Change error rate and data rate and compare the throughputs.

Step 5: View the results in filename.results folder.

Example and Result:

Command used: stcp –p 7000 –l 1024 1.0.1.6


rtcp –p 7000 –l 1024

For 6 nodes:

Error rate: 0.0


Data rate: 10 Mbps

Output throughput:650-1100
Input throughput: 650-1100

Error rate: 1.0


Data rate: 10 Mbps

Output throughput:650-1100
Input throughput: 650-1100

Error rate: 1.0


Data rate: 100 Mbps

Output throughput:1550-9800
Input throughput: 1550-9800

6. Simulate an Ethernet LAN using N nodes and set multiple traffic nodes and
determine collision across different nodes.

Step 1: Connect one set of hosts with a hub and another set of hosts also through a hub and
connect these two hubs through a switch. This forms an Ethernet LAN.

Step 2: Set up multiple traffic connections between the hosts on one hub and hosts on
another hub using the following commands:
stcp [-p port] –l writesize] hostIPaddr
rtcp [-p port] [-l readsize]

Step 3: Set up the collision log at the destination hosts in the MAC layer.

13
Networks Laboratory 2009-10

Step 4: View the results in filename.results folder.

Example and Result:

Command used: stcp –p 7000 –l 1024 1.0.1.6


rtcp –p 7000 –l 1024

Drop at node 5: 325 – 750


Drop at node 4: 275 – 930

7. Simulate an Ethernet LAN using N nodes and set multiple traffic nodes and
plot congestion window for different source / destination.

Step 1: Connect one set of hosts with a hub and another set of hosts also through a hub and
connect these two hubs through a switch. This forms an Ethernet LAN.

Step 2: Set up multiple traffic connections between the hosts on one hub and hosts on
another hub using the following commands:
stcp [-p port] –l writesize] hostIPaddr
rtcp [-p port] [-l readsize]

Step 3: Set up the collision log at the destination hosts in the MAC layer.

14
Networks Laboratory 2009-10

Step 4: To plot the congestion window go to Menu-> Tools-> Plot Graph-> File->Open-
>filename.results->filename.coll.log.

Step 5: View the results in filename.results folder.

Example and Result:

Command used: stcp –p 7000 –l 1024 1.0.1.6


rtcp –p 7000 –l 1024

Drop at node 5: 325 – 750


Drop at node 4: 275 – 930

Node: The only difference between the 6th experiment and the present experiment is that
here we need to plot the congestion window i.e. collision log.

8. Simulate simple ESS and with transmitting nodes in wireless LAN by


simulation and determine the performance with respect to transmission of
packers.

Step 1: Connect a host and two WLAN access points to a router.

Step 2: Setup multiple mobile nodes around the two WLAN access points and set the path
for each mobile node.

Step 3: Set up a TCP connection between the mobile nodes and host using the following
commands:
ttcp –r –u –s [-p port number]

Step 4: Setup the input throughput log at the destination host.

15
Networks Laboratory 2009-10

Step 5: To set the transmission range go to Menu-> Settings-> WLAN mobile-> node-
>show transmission range.

Step 6: To view the results, go to the filename.results folder.

Example and Result:

Command used: ttcp –r –u –s –p 7000


Output throughput:1190

16
Networks Laboratory 2009-10

PART-B

Program No: 01

Error Detecting Code Using CRC-CCITT (16-bit)

Whenever digital data is stored or interfaced, data corruption might occur. Since the
beginning of computer science, developers have been thinking of ways to deal with this
type of problem. For serial data they came up with the solution to attach a parity bit to each
sent byte. This simple detection mechanism works if an odd number of bits in a byte
changes, but an even number of false bits in one byte will not be detected by the parity
check. To overcome this problem developers have searched for mathematical sound
mechanisms to detect multiple false bits. The CRC calculation or cyclic redundancy check
was the result of this. Nowadays CRC calculations are used in all types of communications.
All packets sent over a network connection are checked with a CRC. Also each data block
on your hard disk has a CRC value attached to it. Modern computer world cannot do
without these CRC calculations. So let's see why they are so widely used. The answer is

17
Networks Laboratory 2009-10

simple; they are powerful, detect many types of errors and are extremely fast to calculate
especially when dedicated hardware chips are used.

The idea behind CRC calculation is to look at the data as one large binary number.
This number is divided by a certain value and the remainder of the calculation is called the
CRC. Dividing in the CRC calculation at first looks to cost a lot of computing power, but it
can be performed very quickly if we use a method similar to the one learned at school. We
will as an example calculate the remainder for the character 'm'—which is 1101101 in
binary notation—by dividing it by 19 or 10011. Please note that 19 is an odd number. This
is necessary as we will see further on. Please refer to your schoolbooks as the binary
calculation method here is not very different from the decimal method you learned when
you were young. It might only look a little bit strange. Also notations differ between
countries, but the method is similar.

With decimal calculations you can quickly check that 109 divided by 19 gives a
quotient of 5 with 14 as the remainder. But what we also see in the scheme is that every bit
extra to check only costs one binary comparison and in 50% of the cases one binary
subtraction. You can easily increase the number of bits of the test data string—for example
to 56 bits if we use our example value "Lammert"—and the result can be calculated with 56
binary comparisons and an average of 28 binary subtractions. This can be implemented in
hardware directly with only very few transistors involved. Also software algorithms can be
very efficient.

All of the CRC formulas you will encounter are simply checksum algorithms based
on modulo-2 binary division where we ignore carry bits and in effect the subtraction will be
equal to an exclusive or operation. Though some differences exist in the specifics across
different CRC formulas, the basic mathematical process is always the same:

• The message bits are appended with c zero bits; this augmented message is the
dividend

18
Networks Laboratory 2009-10

• A predetermined c+1-bit binary sequence, called the generator polynomial, is the


divisor

• The checksum is the c-bit remainder that results from the division operation

Table 1 lists some of the most commonly used generator polynomials for 16- and 32-bit
CRCs. Remember that the width of the divisor is always one bit wider than the remainder.
So, for example, you’d use a 17-bit generator polynomial whenever a 16-bit checksum is
required.

CRC-CCITT CRC-16 CRC-32

Checksum
16 bits 16 bits 32 bits
Width

Generator 10001000000100001 11000000000000101 100000100110000010001110110110111


Polynomial

Table 1. International Standard CRC Polynomials

Error detection with CRC

Consider a message represented by the polynomial M(x)


Consider a generating polynomial G(x)
This is used to generate a CRC = C(x) to be appended to M(x).
Note this G(x) is prime.

Steps:

1. Multiply M(x) by highest power in G(x). i.e. add So


much zeros to M(x).
2. Divide the result by G(x). The remainder = C(x).
Special case: This won't work if bitstring =all
zeros. We don't allow such an M(x).But M(x) bitstring
= 1 will work, for example. Can divide 1101 into
1000.
3. If: x div y gives remainder c
that means: x = n y + c
Hence (x-c) = n y
19
Networks Laboratory 2009-10

(x-c) div y gives remainder 0


Here (x-c) = (x+c)
Hence (x+c) div y gives remainder 0
4. Transmit: T(x) = M(x) + C(x)
5. Receiver end: Receive T(x). Divide by G(x), should
have remainder 0.

Note if G(x) has order n - highest power is xn,


then G(x) will cover (n+1) bits
and the remainder will cover n bits.
i.e. Add n bits (Zeros) to message.

Some CRC polynomials that are actually used

Some CRC polynomials

• CRC-8:
x8+x2+x+1

o Used in: 802.16 (along with error correction).

• CRC-CCITT:
x16+x12+x5+1

o Used in: HDLC, SDLC, PPP default

• IBM-CRC-16 (ANSI):
x16+x15+x2+1

• 802.3:
x32+x26+x23+x22 +x16+x12+x11+x10 +x8+x7+x5+x4+x2+x+1

o Used in: Ethernet, PPP option

/** *******************************************************
Prog No.:1 Date:
C Program for ERROR detecting code using CRC-CCITT(16bit)
**********************************************************/
#include<stdio.h>

int a[100],b[100],i,j,len,k,count=0;

//Generator Polynomial:g(x)=x^16+x^12+x^5+1
int gp[]={1,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,1,};

int main()
{
void div();
20
Networks Laboratory 2009-10

system("clear");
printf("\nEnter the length of Data Frame :");
scanf("%d",&len);
printf("\nEnter the Message :");
for(i=0;i<len;i++)
scanf("%d",&a[i]);

//Append r(16) degree Zeros to Msg bits


for(i=0;i<16;i++)
a[len++]=0;

//Xr.M(x) (ie. Msg+16 Zeros)


for(i=0;i<len;i++)
b[i]=a[i];

//No of times to be divided ie. Msg Length


k=len-16;
div();
for(i=0;i<len;i++)
b[i]=b[i]^a[i]; //MOD 2 Substraction
printf("\nData to be transmitted : ");
for(i=0;i<len;i++)
printf("%2d",b[i]);

printf("\n\nEnter the Reveived Data : ");


for(i=0;i<len;i++)
scanf("%d",&a[i]);

div();

for(i=0;i<len;i++)
if(a[i]!=0)
{
printf("\nERROR in Recived Data");
printf("\nERROR is in %d th bit",i+1);
goto END;
}
printf("\nData Recived is ERROR FREE");
END: printf("\nRemender is : ");

for(i=(len-16);i<len;i++)
printf("%d",a[i]);
printf("\n");
}

void div()
{
for(i=0;i<k;i++)
{
if(a[i]==gp[0])
{

21
Networks Laboratory 2009-10

for(j=i;j<17+i;j++)
a[j]=a[j]^gp[count++];
}
count=0;
}
}
/** ******************************************************
**RESULT**
[root@localhost ]# cc prg1.c
[root@localhost ]# ./a.out

Enter the length of Data Frame :4

Enter the Message :1 0 1 1

Data to be transmitted : 1 0
+ 1 1 1 0 1 1 0 0 0 1 0 1 1 0 1 0 1 1

Enter the Reveived Data : 1 0 1 1 1 0 1 1 0 0 0 0 0 1 1 0 1 0


1 1

ERROR in Recived Data


Remender is : 0000000100000000
**********************************************************/

Program No: 02

Frame Sorting Technique

In Computer Networks a frame is a packet which has been encoded for transmission
over a particular link. A packet consists of three elements: the first element is a header,
which marks the beginning of the packet, and the second element is a data area, which
contains the information to be carried in the packet. The third element of packet is a trailer,
which marks the end of the packet. Different communications protocols use different
conventions for distinguishing between the header, data, and footer elements and for
formatting the data.

22
Networks Laboratory 2009-10

So after dividing the packets into the frames each frame transmitted independently
over network. Due to the network congestion or network traffic in between intermediate
routers or network devices the frames may receive in random order at the receiver. To
overcome this problem a frame sequence number is added in the header of each frame at
the transmitter and at the receiving end after receiving all the frames a simple sorting
technique is applied depending on the frame sequence number.

Implementation Algorithm

Steps

1. Read the data


2. Divide the data into frames and add the header
information i.e. Frame number, Frame size, and so on.

23
Networks Laboratory 2009-10

3. Send the frames i.e. randomize the frames depending


on frame number.
4. Sort the frames by using any of the efficient sorting
technique.

/** *******************************************************
Prog No.:2 Date:

C Program for Frame Sorting Technique using Buffers

**********************************************************/
#include<stdio.h>
#include<string.h>

int count=0,i,j,total,size,num,tsize;
char val[100];
void frames();
void trans();
void sort();

struct frame
{
int seq;
int len;

24
Networks Laboratory 2009-10

char data[20];
int flag;
}n[20],m[20],temp;

int main()
{
printf("\nEnter The Data :");
scanf("%s",val);
tsize=strlen(val);
frames();
trans();
sort();
}

void frames()
{
int ch;
total=0;
printf("\nSegmented Frames and Transmiting order at
Sender:\n");
while(total<tsize)
{
n[count].seq=count+1;
size=rand()%10+1;
n[count].len=size;
n[count].flag=0;
j=0;
if((total+size)<tsize)
{
for(i=total,j=0;i<total+size,j<size;i++,j++)
n[count].data[j]=val[i];
n[count].data[j]='\0';
}
else
{
n[count].len=tsize-total;
j=0;
while(total<tsize)
{
n[count].data[j++]=val[total];
total++;
}
n[count].data[j]='\0';
}
total+=size;
count++;
}
printf("\nFSeq No. FLen Flag FData\n");
for(i=0;i<count;i++)
{
printf(" %d\t %d\t%d\t",n[i].seq,

25
Networks Laboratory 2009-10

n[i].len,n[i].flag);
for(j=0;j<n[i].len;j++)
printf("%c",n[i].data[j]);
printf("\n");
}
num=count;
printf("\nEnter 1/0 to countinue :");
scanf("%d",&ch);
if(ch==0)
exit(0);
}

void trans()
{
int ch;
count=0;
printf("\nBegins :\n");
while(count<num)
{
i=rand()%num;
if(n[i].flag==0)
m[count++]=n[i];
n[i].flag=1;
}
printf("\nThe Order of frames Received at Receiving
Terminal :\n");
printf("\nFSeq No. FLen Flag FData\n");
for(i=0;i<count;i++)
{
printf(" %d\t %d\t%d\t",m[i].seq,
m[i].len,m[i].flag);
for(j=0;j<m[i].len;j++)
printf("%c",m[i].data[j]);
printf("\n");
}
printf("\nTotal No. of frames: %d",count);
printf("\nEnter 1/0 to countinue :");
scanf("%d",&ch);
if(ch==0)
exit(0);
}

void sort()
{
for(i=0;i<count;i++)
for(j=i+1;j<count;j++)
if(m[i].seq>m[j].seq)
{
temp=m[i];
m[i]=m[j];
m[j]=temp;

26
Networks Laboratory 2009-10

}
printf("\nSorted Frames at Receiving Terminal :\n");
printf("\nFSeq No. FLen Flag FData\n");
for(i=0;i<count;i++)
{
printf(" %d\t %d\t%d\t",m[i].seq,
m[i].len,m[i].flag);
for(j=0;j<m[i].len;j++)
printf("%c",m[i].data[j]);
printf("\n");
}
}
/** ******************************************************
**RESULT**
[root@localhost ]# cc prg2.c
[root@localhost ]# ./a.out

Enter The Data :abcdefghijjkkllmmnnooppqqrrssttuuvv

Segmented Frames and Transmiting order at Sender:

FSeq No. FLen Flag FData


1 4 0 abcd
2 7 0 efghijj
3 8 0 kkllmmnn
4 6 0 ooppqq
5 4 0 rrss
6 6 0 ttuuvv

Enter 1/0 to countinue :1

Begins :

The Order of frames Received at Receiving Terminal :

FSeq No. FLen Flag FData


5 4 0 rrss
1 4 0 abcd
4 6 0 ooppqq
2 7 0 efghijj
3 8 0 kkllmmnn
6 6 0 ttuuvv

Total No. of frames: 6


Enter 1/0 to countinue :1

Sorted Frames at Receiving Terminal :

FSeq No. FLen Flag FData


1 4 0 abcd
2 7 0 efghijj

27
Networks Laboratory 2009-10

3 8 0 kkllmmnn
4 6 0 ooppqq
5 4 0 rrss
6 6 0 ttuuvv
[root@localhost ]#
**********************************************************/

Program No: 03

Distance Vector Algorithm

Distance Vector Algorithm is a decentralized routing algorithm that requires that


each router simply inform its neighbors of its routing table. For each network path, the
receiving routers pick the neighbor advertising the lowest cost, then add this entry into its
routing table for re-advertisement. To find the shortest path, Distance Vector Algorithm is
based on one of two basic algorithms: the Bellman-Ford and the Dijkstra algorithms.

Routers that use this algorithm have to maintain the distance tables (which is a one-
dimension array -- "a vector"), which tell the distances and shortest path to sending packets
to each node in the network. The information in the distance table is always updated by
exchanging information with the neighboring nodes. The number of data in the table equals
to that of all nodes in networks (excluded itself). The columns of table represent the directly
attached neighbors whereas the rows represent all destinations in the network. Each data

28
Networks Laboratory 2009-10

contains the path for sending packets to each destination in the network and distance/or
time to transmit on that path (we call this as "cost"). The measurements in this algorithm
are the number of hops, latency, the number of outgoing packets, etc.

The starting assumption for distance-vector routing is each node knows the cost of
the link of each of its directly connected neighbors. Next, every node sends a configured
message to its directly connected neighbors containing its own distance table. Now, every
node can learn and update its distance table with cost and next hops for all nodes network.
Repeat exchanging until no more information between the neighbors.

Consider a node A that is interested in routing to destination H via a directly


attached neighbor J. Node A's distance table entry, Dx(Y,Z) is the sum of the cost of the
direct-one hop link between A and J, c(A,J), plus neighboring J's currently known
minimum-cost path (shortest path) from itself(J) to H. That is
Dx(H,J) = c(A,J) + minw{Dj(H,w)} The minw is taken over all the J's
This equation suggests that the form of neighbor-to-neighbor communication that will take
place in the DV algorithm - each node must know the cost of each of its neighbors'
minimum-cost path to each destination. Hence, whenever a node computes a new minimum
cost to some destination, it must inform its neighbors of this new minimum cost.

Figure (a) A subnet. (b) Input from A, I, H, K, and the new routing table for J.

Implementation Algorithm:

1. send my routing table to all my neighbors whenever my


link table changes
2. when I get a routing table from a neighbor on port P
with link metric M:
a. add L to each of the neighbor's metrics
b. for each entry (D, P', M') in the updated
neighbor's table:
i. if I do not have an entry for D, add (D, P,
M') to my routing table
ii. if I have an entry for D with metric M", add
(D, P, M') to my routing table if M' < M"
3. if my routing table has changed, send all the new
entries to all my neighbors.

29
Networks Laboratory 2009-10

/** *******************************************************
Prog No.:3 Date:

C Program for Distance Vector Algorithm to find suitable path


for transmition

**********************************************************/
#include<stdio.h>
#include<stdlib.h>

void rout_table();
int d[10][10],via[10][10];
int i,j,k,l,m,n,g[10][10],temp[10][10],ch,cost;

int main()
{
char ll,mm;
system("clear");
printf("enter the value of no. of nodes\n");
scanf("%d",&n);
/**********************************************************
for(i=0;i<n;i++)
{
printf("enter the route for %d\n",i+1);
for(j=0;j<n;j++)
{
scanf("%d",&g[i][j]);
if(g[i][j]!=999)
d[i][j]=1;
}
}
*********************************************************/
rout_table();
for(i=0;i<n;i++)
for(j=0;j<n;j++)
temp[i][j]=g[i][j];
for(i=0;i<n;i++)
for(j=0;j<n;j++)
via[i][j]=i;
while(1)
{
for(i=0;i<n;i++)
for(j=0;j<n;j++)
if(d[i][j])
for(k=0;k<n;k++)
if(g[i][j]+g[j][k]<g[i][k])
{
g[i][k]=g[i][j]+g[j][k];
via[i][k]=j;
}

30
Networks Laboratory 2009-10

for(i=0;i<n;i++)
{
printf("table for router %c\n" ,i+97);
for(j=0;j<n;j++)
printf("%c:: %d via %c\n" ,j+97,
g[i][j],via[i][j]+97);
sleep(3);
}
for(i=0;i<n;i++)
for(j=0;j<n;j++)
g[i][j]=temp[i][j];

printf("\n do you want to change the cost(1/0)


\n");
scanf("%d",&ch);

if(ch==1)
{
printf("enter the vertices which you want to
change the cost\n");
scanf("%d %d",&l,&m);
printf("enter the cost\n");
scanf("%d",&cost);
g[l-1][m-1]=cost;
g[m-1][l-1]=cost;

for(i=0;i<n;i++)
for(j=0;j<n;j++)
temp[i][j]=g[i][j];
continue;
}
else
break;
}
}

void rout_table()
{
printf("\nEnter the routing table : \n");
printf("\t|");
for(i=1;i<=n;i++)
printf("%c\t",i+96);
printf("\n");
for(i=0;i<=n;i++)
printf("-------");
printf("\n");
for(i=0;i<n;i++)
{
printf("%c |",i+97);
for(j=0;j<n;j++)
{

31
Networks Laboratory 2009-10

scanf("%d",&g[i][j]);
if(g[i][j]!=999)
d[i][j]=1;

}
}
}

/** ******************************************************

**RESULT**

[root@localhost ]# cc prg3.c
[root@localhost ]# ./a.out

enter the value of no. of nodes


4

Enter the routing table :


|a b c d
-----------------------------------
a |999 5 8 3
b |5 999 2 999
c |8 2 999 6
d |3 999 6 999
table for router a
a:: 6 via d
b:: 5 via a
c:: 7 via b
d:: 3 via a
table for router b
a:: 5 via b
b:: 4 via c
c:: 2 via b
d:: 8 via a
table for router c
a:: 7 via b
b:: 2 via c
c:: 4 via b
d:: 6 via c
table for router d
a:: 3 via d
b:: 8 via a
c:: 6 via d
d:: 6 via a

do you want to change the cost(1/0)


1
enter the vertices which you want to change the cost
1 2
enter the cost

32
Networks Laboratory 2009-10

1
table for router a
a:: 2 via b
b:: 1 via a
c:: 3 via b
d:: 3 via a
table for router b
a:: 1 via b
b:: 2 via a
c:: 2 via b
d:: 4 via a
table for router c
a:: 3 via b
b:: 2 via c
c:: 4 via b
d:: 6 via c
table for router d
a:: 3 via d
b:: 4 via a
c:: 6 via d
d:: 6 via a

do you want to change the cost(1/0)


0
[root@localhost ]#

**********************************************************/

33
Networks Laboratory 2009-10

Program No: 04

Client-server socket programming


Sockets are a protocol independent method of creating a connection
between processes. Sockets can be either
Ø Connection based or connectionless: Is a connection established
before communication or does each packet describe the
destination?
Ø Packet based or streams based: Are there message boundaries or
is it one stream?
Ø Reliable or unreliable: Can messages be lost, duplicated,
reordered, or corrupted?

Socket characteristics

Sockets are characterized by their domain, type and transport protocol.


Common domains are:
Ø AF_UNIX: address format is UNIX pathname
Ø AF_INET: address format is host and port number

Common types are:


Ø virtual circuit: received in order transmitted and reliably
Ø datagram: arbitrary order, unreliable

Each socket type has one or more protocols. Ex:


Ø TCP/IP (virtual circuits)
Ø UDP (datagram)

Use of sockets:
Ø Connection–based sockets communicate client-server: the server
waits for a connection from the client
Ø Connectionless sockets are peer-to-peer: each process is
symmetric.

Socket APIs

Ø socket: creates a socket of a given domain, type, protocol (buy a


phone)
Ø bind: assigns a name to the socket (get a telephone number)
Ø listen: specifies the number of pending connections that can be
queued for a server socket. (call waiting allowance)
Ø accept: server accepts a connection request from a client (answer
phone)
Ø connect: client requests a connection request to a server (call)
Ø send, sendto: write to connection (speak)
Ø recv, recvfrom: read from connection (listen)
Ø shutdown: end the call

34
Networks Laboratory 2009-10

Connection-based communication

Server performs the following actions


Ø socket: create the socket
Ø bind: give the address of the socket on the server
Ø listen: specifies the maximum number of connection requests that
can be pending for this process
Ø accept: establish the connection with a specific client
Ø send, recv: stream-based equivalents of read and write (repeated)
Ø shutdown: end reading or writing
Ø close: release kernel data structures

Client performs the following actions


Ø socket: create the socket
Ø connect: connect to a server
Ø send, recv: (repeated)
Ø shutdown
Ø close

TCP-based sockets

35
Networks Laboratory 2009-10

socket API

#include<sys/types.h>
#include<sys /socket.h>
int socket(int domain, int type, int protocol) ;

Returns a file descriptor (called a socket ID) if successful, -1 otherwise. Note that the
socket returns a socket descriptor which is the same as a file descriptor.

The domain is AF_INET.

The type argument can be:


Ø SOCK_STREAM: Establishes a virtual circuit for stream
Ø SOCK_DGRAM: Establishes a datagram for communication
Ø SOCK_SEQPACKET: Establishes a reliable, connection based, two way
communication with maximum message size. (This is not available on most
machines.)

protocol is usually zero, so that type defines the connection within domain.

bind

36
Networks Laboratory 2009-10

#include <sys / types.h>


#include<sys / socket.h>
int bind(int sid, struct sockaddr *addrPtr, int len)

Where
Ø sid: is the socket id
Ø addrPtr: is a pointer to the address family dependent address structure
Ø len: is the size of *addrPtr

Associates a socket id with an address to which other processes can connect. In internet
protocol the address is [ipNumber, portNumber]

sockaddr

For the internet family:

struct sockaddr_in {
sa_family_t sin_family; // = AF INET
in_port_t sin_port; // is a port number
struct in_addr sin_addr; // an IP address
}

listen

#include <sys / types.h>


#include <sys / socket.h>

int listen (int sid, int size) ;

Where size it the number of pending connection requests allowed (typically limited by
Unix kernels to 5). Returns the 0 on success, or -1 if failure.

accept

#include <sys / types.h>


#include <sys / socket.h>

int accept(int sid ,struct sockaddr *addrPtr , int *lenPtr )

Returns the socketId and address of client connecting to socket.


if lenPtr or addrPtr equal zero, no address structure is returned.
lenPtr is the maximum size of address structure that can be called, returns the actual value.
Waits for an incoming request, and when received creates a socket for it.

send

#include <sys / types.h>


#include <sys / socket.h>

int send(int sid ,const char *bufferPtr ,int len ,int flag)

37
Networks Laboratory 2009-10

Send a message. Returns the number of bytes sent or -1 if failure.


(Must be a bound socket).
flag is either
Ø 0: default
Ø MSG OOB: Out-of-band high priority communication

recv

#include <sys / types.h>


#include <sys / socket.h>

int recv ( int sid , char *bufferPtr , int len , int flags)

Receive up to len bytes in bufferPtr. Returns the number of bytes received or -1 on failure.
flags can be either
Ø 0: default
Ø MSG OOB: out-of-bound message
Ø MSG PEEK: look at message without removing

Shutdown

#include <sys / types.h>


#include <sys / socket.h>

int shutdown ( int sid , int how)

Disables sending (how=1 or how=2) or receiving (how=0 or how=2). Returns -1 on failure.

Connect

-this is the first of the client calls

#include <sys / types.h>


#include <sys / socket.h>

int connect ( int sid , struct sockaddr *addrPtr , int len)

Specifies the destination to form a connection with (addrPtr), and returns a 0 if successful,
-1 otherwise.

Port usage

Note that the initiator of communications needs a fixed port to target communications.
This means that some ports must be reserved for these “well known” ports.

Port usage:
Ø 0-1023: These ports can only be binded to by root
Ø 1024-5000: well known ports
Ø 5001-64K-1: ephemeral ports

38
Networks Laboratory 2009-10

/** *******************************************************
Prog No.:5 Date:

C Program for CLIENT SERVER communication that client sends


the file name and the server to send back the contents of the
requested file if present.
SERVER

**********************************************************/
#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<unistd.h>
#include <termios.h>
void error(char *msg)
{
perror(msg);
exit(1);
}
int main(int argc,char *argv[])
{
int sockfd,newsockfd,portno,clilen,n,slen,pid;
char buffer[256],c[200];

39
Networks Laboratory 2009-10

char fname[20];
struct sockaddr_in serv_addr,cli_addr;
FILE *fptr;
printf("\n*******This is server ");
printf("\nEnter server port number : ");
scanf("%d",&portno);
sockfd=socket(AF_INET,SOCK_STREAM,0);
if(sockfd<0)
error("\nERROR opening socket");
bzero((char *)&serv_addr,sizeof(serv_addr));
serv_addr.sin_family=AF_INET;
serv_addr.sin_addr.s_addr=INADDR_ANY;
serv_addr.sin_port=htons(portno);
if(bind(sockfd,(struct sockaddr
*)&serv_addr,sizeof(serv_addr))<0)
perror("\nERROR in binding");
printf("\nNow server is up wating for client");
listen(sockfd,5);
clilen=sizeof(cli_addr);
while(1)
{
newsockfd=accept(sockfd,(struct sockaddr
*)&cli_addr,&clilen);
printf("\n New client requested it sockfd = %d",newsockfd);
pid=fork();
if(pid==0)
{
bzero(fname,20);
close(sockfd);
n=read(newsockfd,fname,20);
printf("\nn Requesting file content %s ",fname);
slen=strlen(fname);
if(n<0)
error("\nERROR reading from socket");
fptr=fopen(fname,"r");
if(fptr==NULL)
{
printf("\nSERVER:file not found");
bzero(buffer,20);
strcpy(buffer,"end1");
write(newsockfd,buffer,4);
close(newsockfd);
fclose(fptr);
_exit(0);
}
printf("\nserver : Following information is send back to
client :- \n\n\n");
while(!feof(fptr))
{
fgets(buffer,79,fptr);

40
Networks Laboratory 2009-10

if(send(newsockfd, buffer, strlen(buffer), 0) == -1)


perror("send");
puts(buffer);
}
strcpy(buffer,"end");
write(newsockfd,buffer,100);
printf("\nserver :file contents are transfered");
fclose(fptr);
close(newsockfd);
printf("\nserver :Process is going to terminate\n");
exit(0);
} //if pid
} //while(1)
}

/** ******************************************************
**RESULT**
AT SERVER SIDE
[root@localhost ]# cc tcps.c
[root@localhost ]# ./a.out
Received the file name : data.txt
File content sent

[root@localhost]#

**********************************************************/
/** *******************************************************
Prog No.:5 Date:

C Program for CLIENT SERVER communication that client sends


the file name and the server to send back the contents of the
requested file if present.
CLIENT

**********************************************************/

#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<netdb.h>
#include<string.h>
#include<unistd.h>
int t=1;
void error(char *msg)
{
perror(msg);
exit(0);
}
int main(int argc,char *argv[])

41
Networks Laboratory 2009-10

{
int sockfd,n,sl,ch;
char fname[20];
struct sockaddr_in serv_addr;
struct hostent *server;
char host[20],buffer[256],buf[2000];
int portno;
printf("\n************This is client :");
bzero(host,20);
printf("\nEnter \n0 - local host \n1 - ip address : ");
scanf("%d",&ch);
if(ch==0)
strcpy(host,"127.0.0.1"); // use inet address of the
server. you can optain it using
else
{
printf("\nEnter the server ip address :");
scanf("%s",host); // "ifconfig" at root
}
printf("\nEnter port no :");
scanf("%d",&portno);//this must be same as servers port
number
printf("\nClient:Enter path with filename( file is
currently at the server) : ");
scanf("%s",fname);
sockfd=socket(AF_INET,SOCK_STREAM,0);
if(sockfd<0)
error("\nerror opening socket\n");
server=gethostbyname(host);
if(server==NULL)
{
fprintf(stderr,"\nerror,no such host\n");
exit(0);
}
bzero((struct sockaddr_in *)&serv_addr,sizeof(serv_addr));
serv_addr.sin_family=AF_INET;
bcopy((char *)server->h_addr,(char
*)&serv_addr.sin_addr.s_addr,server->h_length);
serv_addr.sin_port=htons(portno);
if(connect(sockfd,(struct sockaddr
*)&serv_addr,sizeof(serv_addr))<0)
error("\nerror connecting");
sl=strlen(fname);
n=write(sockfd,fname,strlen(fname));
if(n<0)
error("\nclient:error writing to socket");
bzero(buf,2000);
printf("\nclient:From server following file contents are
received :- \n\n\n");
while(1)
{

42
Networks Laboratory 2009-10

bzero(buf,2000);
if ((n=recv(sockfd, buf, 100, 0)) == -1)
perror("recv");
if(strcmp(buf,"end1") == 0 )
{
printf("\nclient : File not found");
break;
}
if(strcmp(buf,"end") == 0 )
{
close(sockfd);
exit(0);
}
puts(buf);
}
}

/** ******************************************************

**RESULT**
AT CLIENT SIDE

[root@localhost ]# cc tcpc.c
[root@localhost ]# ./a.out 192.168.0.32 data.txt
Data Sent
File Content....

Sockets are a mechanism for exchanging data between


processes. These processes can either be on the same machine,
or on different machines connected via a network. Once a
socket connection is established, data can be sent in both
directions until one of the endpoints closes the connection.
I needed to use sockets for a project I was working
on, so I developed and refined a few C++ classes to
encapsulate the raw socket API calls. Generally, the
application requesting the data is called the client, and the
application servicing the request is called the server. I
created two primary classes, ClientSocket and ServerSocket,
that the client and server could use to exchange data.
[root@localhost ]#

43
Networks Laboratory 2009-10

**********************************************************/

Program No: 05

Client-Server Communication Using Message Queues or FIFO

Message Queues

Message queues are one of the three different types of System V IPC mechanisms.
This mechanism enables processes to send information to each other asynchronously. The
word asynchronous in the present context signifies that the sender process continues with
its execution without waiting for the receiver to receive or acknowledge the information.
On the other side, the receiver does not wait if no messages are there in the queue. The
queue being referred to here is the queue implemented and maintained by the kernel.

Let us now take a look at the system calls associated with this mechanism.

a. msgget: This, in a way similar to shmget, gets a message queue identifier. The
format is

int msgget(ket_t key, int msgflg);

The first argument is a unique key, which can be generated by using ftok algorithm.
The second argument is the flag which can be IPC_CREAT, IPC_PRIVATE, or one

44
Networks Laboratory 2009-10

of the other valid possibilities (see the man page); the permissions (read and/or write)
are logically ORed with the flags. msgget returns an identifier associated with the key.
This identifier can be used for further processing of the message queue associated with
the identifier.

b. msgctl: This controls the operations on the message queue. The format is

int msgctl(int msqid, int cmd, struct msqid_ds *buf);

Here msqid is the message queue identifier returned by msgget. The second
argument is cmd, which indicates which action is to be taken on the message queue.
The third argument is a buffer of type struct msqid_ds. Each message queue has this
structure associated with it; it is composed of records for queues to be identified by the
kernel. This structure also defines the current status of the message queue. If one of the
cmds is IPC_SET, some fields in the msqid_ds structure (pointed by the third
argument) will be set to the specified values. See the man page for the details.

c. msgsnd: This is for sending messages. The format is

int msgsnd(int msqid, struct msgbuf *msgp, size_t msgsz,


int msgflg);

The first argument is the message queue identifier returned by msgget. The second
argument is a structure that the calling process allocates. A call to msgsnd appends a
copy of the message pointed to by msgp to the message queue identified by msqid. The
third argument is the size of the message text within the msgbuf structure. The fourth
argument is the flag that specify one of several actions to be taken as and when a
specific situation arises.

d. msgrcv: This is for receiving messages. The format is

ssize_t msgrcv(int msqid, struct msgbuf *msgp, size_t


msgsz, long msgtyp, int msgflg);

Besides the four arguments mentioned above for msgsnd, we also have msgtyp,
which specifies the type of message requested.

FIFO :

FIFOs (first in, first out) are similar to the working of pipes. One major feature of
pipe is that the data flowing through the communication medium is transient, that is, data
once read from the read descriptor cannot be read again. Also, if we write data continuously
into the write descriptor, then we will be able to read the data only in the order in which the

45
Networks Laboratory 2009-10

data was written. One can experiment with that by doing successive writes or reads to the
respective descriptors.

FIFOs also provide half-duplex flow of data just like pipes. The difference between
fifos and pipes is that the former is identified in the file system with a name, while the latter
is not. That is, fifos are named pipes. Fifos are identified by an access point which is a file
within the file system, whereas pipes are identified by an access point which is simply an
allotted inode. Another major difference between fifos and pipes is that fifos last
throughout the life-cycle of the system, while pipes last only during the life-cycle of the
process in which they were created. To make it more clear, fifos exist beyond the life of the
process. Since they are identified by the file system, they remain in the hierarchy until
explicitly removed using unlink, but pipes are inherited only by related processes, that is,
processes which are descendants of a single process.

/** *******************************************************
Prog No.:6 Date:

C Program for CLIENT SERVER communication using message


Queues or FIFOs as IPC channels that client sends the file
name and the server to send back the contents of the
requested file if present.
SERVER

**********************************************************/

#include<stdio.h>
#include<stdlib.h>
#include<errno.h>
#include<string.h>
#include<fcntl.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>

#define FIFO1_NAME "fifo1"


#define FIFO2_NAME "fifo2"

int main()
{
char p[100],f[100],c[600],ch;

46
Networks Laboratory 2009-10

int num,num2,fl,fd,fd2,flag=0,i=0;

mknod(FIFO1_NAME,S_IFIFO|0666,0);
mknod(FIFO2_NAME,S_IFIFO|0666,0);

printf("\nSERVER online!\n\n");
fd=open(FIFO1_NAME,O_RDONLY);

printf("\nCLIENT online!\n\tWaiting for request....");

if((num=read(fd,p,100))==-1)
perror("\nread ERROR");
else
{
p[num]='\0';
if((fl=open(p,O_RDONLY))<0)
{
printf("\nSERVER:%s not found!",p);
exit(1);
}

else
{
printf("SERVER: %s found! \n\t Transfering
the contents...",p);
fflush(stdout);
fflush(stdin);
stdin=fdopen(fl,"r");

fd2=open(FIFO2_NAME,O_WRONLY);

while(fgets(c,600,stdin)!=NULL)
{
if(num2=write(fd2,c,strlen(c))==-1)
perror("\nTransfer error!");
else
{
flag=1;
//printf("\nSERVER transfer Completed!
");
}
}
close(fd2);
if(flag==0)
{
perror("\nRead ERROR");
exit(1);
}
else
printf("\nSERVER transfer Completed!
\n");

47
Networks Laboratory 2009-10

}
}
return 0;
}

/** ******************************************************

**RESULT**
AT SERVER SIDE

[root@localhost ]# cc -o s prg6s.c
[root@localhost ]# cc -o c prg6c.c
/tmp/cc43imhx.o(.text+0x95): In function `main':
: warning: the `gets' function is dangerous and should not be
used.
[root@localhost Jadhav]# ./s

SERVER online!

CLIENT online!
Waiting for request....SERVER: /Test.txt found!
Transfering the contents...
SERVER transfer Completed!
SERVER transfer Completed!
**********************************************************/

/** *******************************************************
Prog No.:5 Date:

C Program for CLIENT SERVER communication using message


Queues or FIFOs as IPC channels that client sends the file
name and the server to send back the contents of the
requested file if present.
CLIENT

**********************************************************/
#include<stdio.h>
#include<stdlib.h>
#include<errno.h>
#include<string.h>
#include<fcntl.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>

#define FIFO1_NAME "fifo1"


#define FIFO2_NAME "fifo2"

int main()
{
char p[100],f[100],c[600];

48
Networks Laboratory 2009-10

int num,num2,fl,fd,fd2,i=0;

mknod(FIFO1_NAME,S_IFIFO|0666,0);
mknod(FIFO2_NAME,S_IFIFO|0666,0);

printf("\nWaiting for SERVER...");


fd=open(FIFO1_NAME,O_WRONLY);
printf("\nSERVEER online!\n\tCLIENT : Enter the path:
");
gets(p);//,!feof(stdin))
if((num=write(fd,p,strlen(p)))==-1)
perror("\nwrite ERROR");
else
{
printf("\nWating for reply...");
fflush(stdout);
fd2=open(FIFO2_NAME,O_RDONLY);
printf("\nFile recieved! Displaying the
contents:\n\n");
while(num2=read(fd2,c,600)!=0)
fputs(c,stdout);
}
return 0;
}

/** ******************************************************
**RESULT**
AT CLIENT SIDE

[root@localhost ]# ./c

Waiting for SERVER...


SERVEER online!
CLIENT : Enter the path: /Test.txt

Wating for reply...


File recieved! Displaying the contents:

Sockets are a mechanism for exchanging data between


processes. These processes can either be on the same machine,
or on different machines connected via a network. Once a
socket connection is established, data can be sent in both
directions until one of the endpoints closes the connection.
I needed to use sockets for a project I was working
on, so I developed and refined a few C++ classes to
encapsulate the raw socket API calls. Generally, the
application requesting the data is called the client, and the
application servicing the request is called the server. I
created two primary classes, C ZlientSocket and ServerSocket,
that the client and server could use to exchange data.

49
Networks Laboratory 2009-10

[root@localhost ]#

**********************************************************/

/** *******************************************************
Prog No.:5 Date:

C Program for CLIENT SERVER communication using message


Queues or FIFOs as IPC channels that client sends the file
name and the server to send back the contents of the
requested file if present.
Message Q - Client

**********************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <errno.h>
#include <string.h>

#define NMSGS 5

extern int errno;

struct msgbuf
{
long mtype;

50
Networks Laboratory 2009-10

char mtext[100];
};

int main()
{
int msgid;
int i, nloop;
struct msgbuf msgp;

char tmp_msg[100];

tmp_msg[0] = '\0';

msgid = msgget(9999, IPC_CREAT | 0666);

if(msgid < 0)
{
printf("%d : Error number is %d\n", __LINE__,
errno);
exit(1);
}

for(nloop=0;nloop<NMSGS;nloop++)
{
msgp.mtype = 1;
fgets(tmp_msg, 100, stdin);

strncpy(msgp.mtext, tmp_msg, strlen(tmp_msg));


i = msgsnd(msgid, &msgp, strlen(tmp_msg),
IPC_NOWAIT);
if(i < 0)
{
printf("%d : Error number is %d\n",
__LINE__, errno);
exit(1);
}
tmp_msg[0] = '\0';
}

return 0;
}
/*********************************************************

**RESULT**

[root@localhost ]# ./msgc
Hi
Hello

51
Networks Laboratory 2009-10

[root@localhost ]#

**********************************************************/

/** *******************************************************
Prog No.:5 Date:

C Program for CLIENT SERVER communication using message


Queues or FIFOs as IPC channels that client sends the file
name and the server to send back the contents of the
requested file if present.
Message Q - SERVER

**********************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <errno.h>
#include <string.h>

extern int errno;

struct msgbuf
{
long mtype;

52
Networks Laboratory 2009-10

char mtext[100];
};

int main()
{
int msgid;
int i, nloop;
struct msgbuf msgp;

msgid = msgget(9999, 0444);


if(msgid < 0)
{
printf("%d : Error number is %d\n", __LINE__,
errno);
exit(1);
}

for(nloop=0;nloop<5;nloop++)
{
bzero(msgp.mtext, 100);
i = msgrcv(msgid, &msgp, 100, 1, IPC_NOWAIT);

if(i < 0)
{
printf("%d : Error number is %d\n",
__LINE__, errno);
exit(1);
}

msgp.mtext[strlen(msgp.mtext)] = '\0';

//fwrite(msgp.mtext, sizeof(char),
strlen(msgp.mtext), stdout);
printf("message is: %s\n", msgp.mtext);
}

if(msgctl(msgid, IPC_RMID, NULL) < 0)


{
printf("%d : Error number is %d\n", __LINE__,
errno);
exit(1);
}

return 0;
}

/*********************************************************
**RESULT**

53
Networks Laboratory 2009-10

[root@localhost ]# cc -o msgs prg6s1.c


[root@localhost ]# cc -o msgc prg6c1.c
[root@localhost ]# ./msgs

message is: Hi

message is: Hello

47 : Error number is 42
[root@localhost ]#

**********************************************************/

Program No: 06

RSA Algorithm to Encrypt and Decrypt the Data

The RSA algorithm can be used for both public key encryption and digital
signatures. Its security is based on the difficulty of factoring large integers.

The RSA algorithm's efficiency requires a fast method for performing the modular
exponentiation operation. A less efficient, conventional method includes raising a number
(the input) to a power (the secret or public key of the algorithm, denoted e and d,
respectively) and taking the remainder of the division with N. A straight-forward
implementation performs these two steps of the operation sequentially: first, raise it to the
power and second, apply modulo.

A very simple example of RSA encryption

This is an extremely simple example using numbers you can work out on a pocket
calculator (those of you over the age of 35 can probably even do it by hand on paper).

1. Select primes p = 11, q = 3.

54
Networks Laboratory 2009-10

2. n = pq = 11.3 = 33
phi = (p-1)(q-1) = 10.2 = 20

3. Choose e=3
Check gcd(e, p-1) = gcd(3, 10) = 1 (i.e. 3 and 10 have
no common factors except 1),
and check gcd(e, q-1) = gcd(3, 2) = 1
therefore gcd(e, phi) = gcd(e, (p-1)(q-1)) = gcd(3, 20)
= 1

4. Compute d such that ed ≡ 1 (mod phi)


i.e. compute d = e^-1 mod phi = 3^-1 mod 20
i.e. find a value for d such that phi divides (ed-1)
i.e. find d such that 20 divides 3d-1.
Simple testing (d = 1, 2, ...) gives d = 7
Check: ed-1 = 3.7 - 1 = 20, which is divisible by phi.

5. Public key = (n, e) = (33, 3)


Private key = (n, d) = (33, 7).

This is actually the smallest possible value for the modulus n for which the RSA
algorithm works.

Now say we want to encrypt the message m = 7,


c = m^e mod n = 7^3 mod 33 = 343 mod 33 = 13.
Hence the ciphertext c = 13.

To check decryption we compute


m' = c^d mod n = 13^7 mod 33 = 7.

Note that we don't have to calculate the full value of 13 to the power 7 here. We can
make use of the fact that a = bc mod n = (b mod n).(c mod n) mod n so we can break down
a potentially large number into its components and combine the results of easier, smaller
calculations to calculate the final value.

One way of calculating m' is as follows:-

m' = 13^7 mod 33 = 13^(3+3+1) mod 33 = 13^3.13^3.13 mod 33


= (13^3 mod 33).(13^3 mod 33).(13 mod 33) mod 33
= (2197 mod 33).(2197 mod 33).(13 mod 33) mod 33
= 19.19.13 mod 33 = 4693 mod 33
= 7.

Now if we calculate the cipher text c for all the possible values of m (0 to 32), we get

m 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
c 0 1 8 27 31 26 18 13 17 3 10 11 12 19 5 9 4

m 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
c 29 24 28 14 21 22 23 30 16 20 15 7 2 6 25 32

55
Networks Laboratory 2009-10

Note that all 33 values of m (0 to 32) map to a unique code c in the same range in a
sort of random manner. In this case we have nine values of m that map to the same value of
c - these are known as unconcealed messages. m = 0 and 1 will always do this for any N,
no matter how large. But in practice, higher values shouldn't be a problem when we use
large values for N.

If we wanted to use this system to keep secrets, we could let A=2, B=3, ..., Z=27.
(We specifically avoid 0 and 1 here for the reason given above). Thus the plaintext message
"HELLOWORLD" would be represented by the set of integers m1, m2, ...

{9,6,13,13,16,24,16,19,13,5}

Using our table above, we obtain ciphertext integers c1, c2, ...

{3,18,19,19,4,30,4,28,19,26}

Note that this example is no more secure than using a simple Caesar substitution
cipher, but it serves to illustrate a simple example of the mechanics of RSA encryption.

Remember that calculating m^e mod n is easy, but calculating the inverse c^-e mod
n is very difficult, well, for large n's anyway. However, if we can factor n into its prime
factors p and q, the solution becomes easy again, even for large n's. Obviously, if we can
get hold of the secret exponent d, the solution is easy, too.

Key Generation Algorithm


1. Generate two large random primes, p and q, of
approximately equal size such that their product n =
pq is of the required bit length, e.g. 1024 bits.
[See note 1].
2. Compute n = pq and (φ) phi = (p-1)(q-1).
3. Choose an integer e, 1 < e < phi, such that gcd(e,
phi) = 1. [See note 2].
4. Compute the secret exponent d, 1 < d < phi, such that

ed ≡ 1 (mod phi). [See note 3].


5. The public key is (n, e) and the private key is (n,
d). The values of p, q, and phi should also be kept
secret.

• n is known as the modulus.

• e is known as the public exponent or encryption exponent.

• d is known as the secret exponent or decryption exponent.

Encryption
Sender A does the following:-
56
Networks Laboratory 2009-10

1. Obtains the recipient B's public key (n, e).

2. Represents the plaintext message as a positive integer m [see note 4].

3. Computes the ciphertext c = m^e mod n.

4. Sends the ciphertext c to B.

Decryption
Recipient B does the following:-

1. Uses his private key (n, d) to compute m = c^d mod n.

2. Extracts the plaintext from the integer representative m.

/** *******************************************************
Prog No.:6 Date:

C Program for Simple RSA Algorithm to encrypt and decrypt the


data

**********************************************************/
#include<stdio.h>
#include<conio.h>
#include<math.h>

int e,n,d;
void main()
{
int i,p,q,phi;
char ptext[30],ctext[30],rptext[30];
clrscr();

57
Networks Laboratory 2009-10

printf("Select the two primes P and Q (recommended: 3 and


11)\n");
scanf("%d %d",&p,&q);
n=p*q;
phi=(p-1)*(q-1);
printf("\nEnter the public exponent(recommended:3):\n");
scanf("%d",&e);
if((gcd(e,p-1)!=1)||(gcd(e,q-1)!=1)||(gcd(e,phi)!=1))
{
printf("\nIncorrect values");
exit(1);
}
d=pri_key(phi);
printf("\n\nPublic key : (%d, %d)",n,e);
printf("\n\nPrivate key : (%d, %d)",n,d);
printf("\n\n\nEnter the text(in UPPER CASE LETTERS) :");
scanf("%s",ptext);
for(i=0;i<strlen(ptext);i++)
ctext[i]=encr(ptext[i]-63);
printf("\n\nEncrypted Text is:\n");
for(i=0;i<strlen(ptext);i++)
printf("%c",ctext[i]+63);
for(i=0;i<strlen(ptext);i++)
rptext[i]=decr(ctext[i]);
printf("\n\nDecrypted Text is:\n");
for(i=0;i<strlen(ptext);i++)
printf("%c",rptext[i]+63);
getch();
}

int gcd(int a, int b)


{
while(a!=b)
{
if(a>b)
a=a-b;
else
b=b-a;
}
return a;
}

int pri_key(int phi)


{
int i=0;
while(++i)
if((((3*i)-1)%phi)==0)
return i;
}

int encr(int m)

58
Networks Laboratory 2009-10

{
return((int)pow(m,e)%n);
}

int decr(int c)
{
return ((int)pow(c,(d%e))%n)*((int)pow((int)pow(c,e)
%n,d/e))%n;
}

/*********************************************************
**RESULT**
[root@localhost ]# cc prg7.c
[root@localhost ]# ./a.out

RSA Algorithm
Select the two primes P and Q (recommended : 3 and 11)
11
3
Enter the public exponent ((recommended : 3)
3

Public key : 33, 3


Private key : 33, 7

Enter the text(in UPPER CASE LETTERS) :


HELLO

Encrepted Text is: B Q R R C

Dercypted Text is: H E L L O

root@localhost ]#
**********************************************************/
Program No: 07

Hamming Code Generation for Error Detection and Correction

Forward Error Correction (FEC) gains ability to receiving stations to correct a


transmission error, which improves the throughput of a data link operating in a noisy
environment. In order to perform the error correction, the transmitting station must append
information to the data in a form of error correction bits, but the increase in frame length
will slow down the transmission process. Hamming codes provide for FEC using a “block
parity” mechanism that can be inexpensively implemented. In general, their use allows the
correction of single bit errors and detection of two bit errors per unit data, called a code
word.

Hamming codes use parity principal to correct one error or detect two errors, but
they are not capable of doing both simultaneously. One can use Hamming codes as an error
59
Networks Laboratory 2009-10

detector to catch both single and double bit errors, or use them as an error corrector to
modify single bit error. This is accomplished by using more than one parity bit, each
computed on different combination of bits in the data.

The number of parity or error check bits required is given by the Hamming rule, and
is a function of the number of bits of information transmitted. The Hamming rule is
expressed by the following inequality:

d + p + 1 < = 2p

Where d is the number of data bits and p is the number of parity bits. The result of
appending the computed parity bits to the data bits is called the Hamming code word. The
size of the code word c is obviously d+p, and a Hamming code word is described by the
ordered set (c,d).

Codes with values of p< =2 are hardly worthwhile because of the overhead
involved. Therefore I will use a case when p=3 and develop a (7,4) code using even parity.
7 is the total bits of the code word, while 4 is the data bits in the code word. In real
application larger code word are usually used.

A Hamming code word is generated by multiplying the data bits by a generator


matrix G using “modulo-2 arithmetic.” This multiplication's result is called the code word
vector (c1,c2.c3,.....cn), consisting of the original data bits and the calculated parity bits.

The generator matrix G used in constructing Hamming codes consists of I (the


identity matrix) and a parity generation matrix A:

G = [ I : A ]

An example of Hamming Code generator matrix:

1 0 0 0 | 1 1 1
G = 0 1 0 0 | 0 1 1
0 0 1 0 | 1 0 1
0 0 0 1 | 1 1 0

The multiplication of a 4-bit vector (d1,d2,d3,d4) by G results in a 7-bit code word


vector of the form (d1,d2,d3,d4,p1,p2,p3). It is clear that the A partition of G is responsible
for the generation of the actual parity bits. Each column in A represents one parity
calculation computed on a subset of d. The Hamming rule requires that p=3 for a (7,4)
code, therefore A must contain three columns to produce three parity bits.

If the columns of A are selected so each column is unique, it follows that (p1,p2,p3)
represents parity calculations of three distinct subset of d. As shown in the figure below,

60
Networks Laboratory 2009-10

validating the received code word r, involves multiplying it by a parity check to form s, the
syndrome or parity check vector.

H = [AT | I]

|1|
|0|
| 1 0 1 1 | 1 0 0 | |0| |0|
| 1 1 0 1 | 0 1 0 | * |1| = |0|
| 1 1 1 0 | 0 0 1 | |0| |0|
|0|
|1|

H*r = s

If all elements of s are zero, the code word was received correctly. If s contains non-
zero elements, the bit in error can be determined by analyzing which parity checks have
failed, as long as the error involves only a single bit.

For instance if r=[1011001], s computes to [101], that syndrome ([101]) matches to


the third column in H that corresponds to the third bit of r - the bit in error.

Implementation Algorithm:

1. Read the message.


2. Convert it to binary format & group the bits into 4
3. While(message_bits) // Encoding
a. Calculate the Hamming Parity as following bit
positions
Bit 5 = bit 1 + bit 3 + bit 4
Bit 6 = bit 1 + bit 2 + bit 4
Bit 7 = bit 2 + bit 3 + bit 4
4. Decode for i 1 to 3
a. for j 1 to 7
i. reminder[m] = hamming_matrix[i][j] *
recived_codeword[j];
ii. convert reminder to binary;
b. if(reminder is non zero then compare it with
hamming_matrix columns if matches)
ERROR in that particular bit;

61
Networks Laboratory 2009-10

Else
Data received is error free.
5. End

/** *******************************************************
Prog No.:7 Date:

C Program for Hamming code generation for ERROR detecting and


correction

**********************************************************/
#include<stdio.h>
#include<stdlib.h>

int mm[30];

int main()
{
int b[10],n,k=0,i,m,s[10],j=0,flag=0,l,len;
int ll=1,kk=0,jj=0;
int a[4][8]={
{0,0,0,0,0,0,0,0},

62
Networks Laboratory 2009-10

{0,1,0,1,1,1,0,0},
{0,1,1,0,1,0,1,0},
{0,0,1,1,1,0,0,1}
};
char mess[40];

system("clear");
printf("Enter the message:\n");
scanf("%s",&mess);

len=strlen(mess);

for(i=0;i<len;i++)
{
k=mess[i];
k%=16;
while(k!=0)
{
mm[jj++]=k%2;
k=k/2;
}
while(jj%4!=0)
mm[jj++]=0;
}
k=0;
while(kk<jj)
{
do
{
b[ll++]=mm[kk++];
}while(kk%4!=0);

ll=1;

b[5]=(b[1]+b[3]+b[4])%2;
b[6]=(b[1]+b[2]+b[4])%2;
b[7]=(b[2]+b[3]+b[4])%2;

printf("\ncodeword of %c\n",mess[k]);
for(i=1;i<=7;i++)
printf("%d ",b[i]);
printf("\n");

printf("\nEnter the codeword recieved by receiver


\n");
for(i=1;i<=7;i++)
scanf("%d",&b[i]);
b[0]=0;
for(m=0;m<=3;m++)
s[m]=0;
m=0;

63
Networks Laboratory 2009-10

for(i=0;i<=3;i++)
{
for(j=0;j<=7;j++)
{
s[m]=s[m]+(a[i][j]*b[j]);
s[m]=s[m]%2;
}
m++;
}
for(i=1;i<=3;i++)
printf(" %d",s[i]);
printf("\n");
for(i=1;i<=7;i++)
{
for(j=1;j<=3;j++)
{
if(s[j]==a[j][i])
flag=1;
else
{
flag=0;
break;
}
}
if(flag)
{
printf("error is at %d\n",i);
if(b[i])
b[i]=0;
else
b[i]=1;
}
}
printf("Corrected codeword for %c \n",mess[k]);
for(i=1;i<=7;i++)
printf("%d ",b[i]);
printf("\n");
k++;
}
}
/** *****************************************************
**RESULT**
[root@localhost ]# cc prg8.c
[root@localhost ]# ./a.out

Enter the message:


Hi

codeword of H
0 0 0 1 1 1 1

64
Networks Laboratory 2009-10

Enter the codeword recieved by reciever


0 0 0 1 1 1 1
0 0 0
Corrected codeword for H
0 0 0 1 1 1 1

codeword of i
1 0 0 1 0 0 1

Enter the codeword recieved by reciever


1 0 0 0 0 0 1
1 1 1
error is at 4
Corrected codeword for i
1 0 0 1 0 0 1
[root@localhost ]#
**********************************************************/

Program No: 08

Congestion Control Using Leaky Bucket Algorithm

The main concept of the leaky bucket algorithm is that the output data flow remains
constant despite the variant input traffic, such as the water flow in a bucket with a small
hole at the bottom. In case the bucket contains water (or packets) then the output flow
follows a constant rate, while if the bucket is full any additional load will be lost because of
spillover. In a similar way if the bucket is empty the output will be zero.
From network perspective, leaky bucket consists of a finite queue (bucket) where all the
incoming packets are stored in case there is space in the queue, otherwise the packets are
discarded. In order to regulate the output flow, leaky bucket transmits one packet from the
queue in a fixed time (e.g. at every clock tick). In the following figure we can notice the
main rationale of leaky bucket algorithm, for both the two approaches (e.g. leaky bucket
with water (a) and with packets (b)).

65
Networks Laboratory 2009-10

Figure 2.4 - The leaky bucket traffic shaping algorithm

While leaky bucket eliminates completely bursty traffic by regulating the incoming
data flow its main drawback is that it drops packets if the bucket is full. Also, it doesn’t
take into account the idle process of the sender which means that if the host doesn’t
transmit data for some time the bucket becomes empty without permitting the transmission
of any packet.

Implementation Algorithm:

Steps:

1. Read The Data For Packets


2. Read The Queue Size
3. Divide the Data into Packets
4. Assign the random Propagation delays for each packets to
input into the bucket (input_packet).
5. wlile((Clock++<5*total_packets)and
(out_packets< total_paclets))
a. if (clock == input_packet)
i. insert into Queue
b. if (clock % 5 == 0 )
i. Remove paclet from Queue
6. End

66
Networks Laboratory 2009-10

/*********************************************************
Prog No.:8 Date:

C Program for Congestion control using Leaky Bucket Algorithm

**********************************************************/
#include<stdio.h>
#include<strings.h>

struct pack
{
int seq;
char text[20];
}p[100];

int at[10],q[10],c,clk,qs,fp,rp=1,pi,np=1,in;

int main()
{

67
Networks Laboratory 2009-10

int n_it=0,i,j=0,r,n;
char msg[100];
printf("\nEnter The Message :");
fflush(stdin);
fflush(stdout);
scanf("%s",msg);
fflush(stdin);
printf("\nEnter The Q Size :");
scanf("%d",&qs);

n_it=strlen(msg)%5;
if(strlen(msg)%5)
n_it++;
while(n_it!=1)
{
p[np].seq=np;
for(i=0;i<5;i++)
p[np].text[i]=msg[j++];
p[np].text[i]='\0';
np++;
n_it--;
}

display();
at[0]=1;
for(i=1;i<np;i++)
{
n=rand()%6;
at[i]=at[i-1]+n;
}
i=0;

while(clk<(5*(np))||(in<np))
{
sleep(3);
printf("\nClock :%d\n",clk);
if(clk==at[i])
{
i++;
insert();
}
if(clk%5==0)
del();
clk++;
}
printf("\nDone");
}

del()

68
Networks Laboratory 2009-10

{
if(c==0)
{
printf("\nNo Packets To Delete\n");
return;
}
printf("\nDeletion-->%d--> %s\n",
p[q[fp]].seq,p[q[fp]].text);
fp=(fp+1)%qs;
c--;
}

insert()
{
in++;
if(c==qs)
{
printf("\nBucket Overflow\n");
printf("Packet Lost is-->%d-->%s\n",
pi,p[pi].text);
pi++;
return;
}
rp=(rp+1)%qs;
q[rp]=pi++;
printf("\nInsertion-->%d-->%s\n",
p[q[rp]].seq,p[q[rp]].text);
c++;
}

display()
{
int i;
printf("\nFragmented Pckets :\n");
for(i=0;i<np-1;i++)
printf("\n%d--->%s\n",p[i].seq,
p[i].text);
}
/** ******************************************************
**RESULT**
[root@localhost ]# cc prg9.c
[root@localhost ]# ./a.out

Enter The Message :abcdefghijklmn

Enter The Q Size :2

Fragmented Pckets :

0--->

69
Networks Laboratory 2009-10

1--->abcde

2--->fghij

3--->klmn

Clock :0

No Packets To Delete

Clock :1

Insertion-->0-->

Clock :2

Insertion-->1-->abcde

Clock :3

Clock :4

Clock :5

Deletion-->0-->

Clock :6

Insertion-->2-->fghij

Clock :7

Clock :8

Clock :9

Bucket Overflow
Packet Lost is-->3-->klmn

Clock :10

Bucket Overflow
Packet Lost is-->4-->

Deletion-->1-->abcde

Clock :11

Clock :12

Clock :13

70
Networks Laboratory 2009-10

Clock :14

Clock :15

Deletion-->2-->fghij

Clock :16

Clock :17

Clock :18

Clock :19

Clock :20

No Packets To Delete

Clock :21

Clock :22

Clock :23

Clock :24

Done
[root@localhost]#

**********************************************************/

71