CN Lab Final
CN Lab Final
CN Lab Final
Introduction to NCTUns
Introduction
NCTUns is open source, high quality, and supports many types of networks.The NCTUns
is a high-fidelity and extensible network simulator and emulator capable of simulating various protocols
used in both wired and wireless IP networks. Its core technology is based on the novel kernel re-entering
methodology invented by Prof. S.Y. Wang [1, 2] when he was pursuing his Ph.D. degree at Harvard
University. Due to this novel methodology, NCTUns provides many unique advantages that cannot be
easily achieved by traditional network simulators such as ns-2 [3] and OPNET [4].
After obtaining his Ph.D. degree from Harvard University in September 1999, Prof. S.Y. Wang
returned to Taiwan and became an assistant professor in the Department of Computer Science and
Information Engineering, National Chiao Tung University (NCTU), Taiwan, where he founded his
“Network and System Laboratory.” Since that time, Prof. S.Y. Wang has been leading and working with
his students to design and implement NCTUns (the NCTU Network Simulator) for more than five years.
● It 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. By using a novel kernel re-entering simulation methodology, a real-life UNIX (e.g., Linux)
kernel’s protocol stack can be directly used 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 moved to
and used on real-world UNIX machines 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. For example, the UNIX
route, ifconfig, netstat, tcpdump, traceroute commands can be run on a simulated network to
configure or monitor the simulated network.
● 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. A wired network is composed of fixed nodes and point-to-point links. Traditional
circuit-switching optical networks and more advanced Optical Burst Switching (OBS) networks are
also supported. A wireless networks is composed of IEEE 802.11 (b) mobile nodes and access points
(both the ad-hoc mode and infra-structure mode are supported). GPRS cellular networks are also
supported.
● 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.
● Its simulation speed is high. By combining the kernel re-entering methodology with the discrete-
event simulation methodology, a simulation job can be finished quickly.
● Its simulation results are repeatable. If the chosen random number seed for a simulation case is fixed,
the simulation results of a case are the same across different simulation runs even though there are
some other activities (e.g., disk I/O) occurring on the simulation machine.
● 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) playing back the animation of a
logged packet transfer trace, etc. All these operations can be easily and intuitively done with the GUI.
● Its simulation engine adopts an open-system architecture and is open source. By using a set of
module APIs provided by the simulation engine, a protocol module writer can easily implement his
(her) protocol and integrate it into the simulation engine. 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. However, if a researcher wants to try his (her) novel device or
network configurations that the current GUI does not support, he (she) can totally bypass the GUI and
generate the suite of description files by himself (herself) using any text editor (or script program).
The non-GUI-generated suite of files can then be manually fed to the simulation engine for execution.
● It supports remote and concurrent simulations. NCTUns adopts a distributed architecture. The GUI
and simulation engine are separately implemented and use the client-server model to communicate.
Therefore, a remote user using the GUI program can remotely submit his (her) simulation job to a
server running the simulation engine. The server will run the submitted simulation job and later return
the results back to the remote GUI program for analyzes. This scheme can easily support the cluster-
computing model in which multiple simulation jobs are performed in parallel on different server
machines. This can increase the total simulation throughput.
● It supports more realistic wireless signal propagation models. In addition to providing the simple
(transmission range = 250 m, interference range = 550 m) model that is commonly used in the ns-2,
NCTUns provides a more realistic model in which a received bit’s BER is calculated based on the
used modulation scheme, the bit’s received power level, and the noise power level around the
receiver. Large-scale path loss and small-scale fading effects are also simulated.
GETTING STARTED
A user using the NCTUns in single machine mode, needs to do the following steps before he/she
starts the GUI program:
After the above steps are followed, the starting screen of NCTUns disappears and the user is presented
with the working window.
PART-A
1. Simulate a three-node point-to-point network with a duplex link between them. Set the queue
size and vary the bandwidth and find the number of packets dropped.
STEPS:
Step1: Create a topology as shown in the below figure.
Step 2: Select the hub icon on the toolbar and drag it onto the working window.
Step 3: Select the host icon on the toolbar and drag it onto the working window. Repeat this for another
host icon.
Step 4: Select the link icon on the toolbar and drag it on the screen from host (node 1) to the hub and
again from host(node 2) to the hub. Here the hub acts as node 3 in the point-to-point network. This leads
to the creation of the 3-node point-to-point network topology. Save this topology as a .tpl file.
Step 5:Double-click on host(node 1), a host dialog box will open up. Click on Node editor and you can
see the different layers- interface, ARP,FIFO, MAC, TCPDUMP, Physical layers. Select MAC
and then select full-duplex for switches and routers and half duplex for hubs, and in log
Statistics, select Number of Drop Packets, Number of Collisions, Throughput of incoming packets and
Throughput of outgoing packets. Then click on Add. Another dialog box pops up.
Click on the Command box and type the following Command.
Step 6: Double-click on host (node 2), and follow the same step as above with only change in command
according to the following syntax:
rtcp –p 3000 –l 1024 and click OK.
Step 7: Click on the E button (Edit Property) present on the toolbar in order to save the changes made to
the topology. Now click on the R button (Run Simulation). By doing so a user can
run/pause/continue/stop/abort/disconnect/reconnect/submit a simulation. No simulation settings
can be changed in this mode.
Step 8: Now go to Menu->Simulation->Run. Executing this command will submit the current
Simulation job to one available simulation server managed by the dispatcher. When the
simulation server is executing, the user will see the time knot at the bottom of the screen move.
The time knot reflects the current virtual time (progress) of the simulation case.
Step 9: After the simulation is completed, click on the play button and mean while plot the graphs of the
drop packets and through put input and through put output. These log files are created in
filename.results folder.
Step 10. Now click on the link (connecting the hub and host2) and change the bandwidth say, 9 Mbps,
and run the simulation and compare the two results.
Graphs Sheet:
By setting the bandwidth as 10 Mbps on both the links and queue size as 50 we obtain the following
results:
Output throughput (host 1) = 1177
By changing bandwidth to 9Mbps in the destination link, we obtain the following results:
Results: By setting the bandwidth as 10 Mbps on both the links and queue size as 50 we obtain the
following results:
output throughput (host 1) = 1190
By changing bandwidth to 9Mbps in the destination link, we obtain the following results:
2. Simulate a four-node point-to-point network and connect the link as follows: Apply a TCP agent
between n0 to n3 and apply a UDP agent between n1 and n3. Apply relevant applications over
TCP and UDP agents changing the parameters and determine the number of packets sent by two
agents.
STEPS:
Step1: Create a topology as shown in the below figure.
Step 2: Select 3 Nodes (1,2,3) and connect them using a hub(4) as shown in above.
Step 3: Go to edit mode and save the topology.
Step 4 a : Double click on host (Node 1) and goto node editor, and click on MAC 8023 and put a check
on the Throughput of Outgoing Packets. Click ok. Then click on ADD and type the following
command.
stcp –p 3000 –l 1024 1.0.1.3 and click OK
Here 1.0.1.3 is the IP address of the Host 3 (Receiver) and 3000 is the port no.
Step 4 b : Double-click on host (node 2), and follow the same step as above with only change in
command according to the following syntax:
Graphs Sheet:
Results: By setting the bandwidth as 100 Mbps on the TCP link and queue size as 50 we obtain the
following results:
3. Simulate the transmission of ping messages over a network topology consisting of 6 nodes and
find the number of packets dropped due to congestion.
STEPS:
Step1: Create a topology as shown in the below figure.
Step 2: Select 6 Nodes (1-6) and connect them using a hub(7) as shown in above.
Step 3: Go to edit mode and save the topology.
Step 4 a : Let us say, Node1 and node 6 are source and destination. Double click on host (Node 1) and
goto node editor, and click on MAC 8023 and put a check on the Collision and packets
dropped. Click ok. Then click on ADD and type the following command.
stcp –p 3000 –l 1024 1.0.1.6 click ok.
Here 1.0.1.6 is the IP address of the Host 6 (Receiver) and 3000 is the port no.
Step 4 b : Double-click on host (node 6 ), and follow the same step as above and type the following
commands:
rtcp –p 3000 –l 1024 and click OK
Step 7: After the simulation is completed, click on the play button and mean while plot the graphs of the
Collision and packets dropped.. These log files are created in filename.results folder.
Graphs Sheet:
4. Simulate an Ethernet LAN using N nodes (6-10), change error rate and data rate and compare
throughput.
STEPS:
Step1: Create a topology as shown in the below figure.
Step 2: Select 6 Nodes (1-6) and connect them using a hub(7) as shown in above.
Step 3: Go to edit mode and save the topology.
Step 4 a : Let us say, Node1 and node 6 are source and destination. Double click on host (Node 1) and
goto node editor, and click on MAC 8023 and put a check on the Throughput of Outgoing
Packets. Click ok. Then click on ADD and type the following command.
Here 1.0.1.6 is the IP address of the Host 6 (Receiver) and 3000 is the port no.
Step 4 b : Double-click on host (node 6 ), and follow the same step as above and check on Throughput
Of Incoming Packets. And type the following commands: rtcp –p 3000 –l 1024
Step 5: Click on R Button and then goto Menu->Simulation->Run.
Step 6: After the simulation is completed, click on the play button and mean while plot the graphs of the
Throughput Input and Throughput Output. These log files are created in filename.results
folder.
Step 7: Change error rate and data rate in Physical layer and then run the simulation again and compare
the Throughput Input and Throughput Output of 1st and 2nd reading.
Graphs Sheet:
Results:
Commands: stcp -p 3000 -l 1024 1.0.1.6
5. Simulate an Ethernet LAN using N nodes and set multiple traffic nodes and plot congestion
window for different source/destination.
STEPS:
Step1: Create a topology as shown in the below figure.
Step 2: Select 6 Nodes (1-6) and connect them using a hub(7) as shown in above.
Step 3: Go to edit mode and save the topology.
Step 4 a : Let us say, Node1 and node 6 are source and destination. Double click on host (Node 1) and
goto node editor, and click on MAC 8023 and put a check on the Collision and Packets
Dropped. Click ok. Then click on ADD and type the following command.
6. Simulate simple ESS and with transmitting nodes in wireless LAN by simulation and determine
the performance with respect to transmission of packets.
STEPS:
Step 2: Setup multiple mobile nodes around the two WLAN access points and set the path for each
mobile node.
Step 3: Setup a ttcp connection between the mobile nodes and host using the following command:
PART-B
Overview:
The accurate implementations (long-hand and programmed) of the 16-bit CRC-CCITT
specification, is as follows:
● Width = 16 bits
● Truncated polynomial = 0x1021
● Initial value = 0xFFFF
● Input data is NOT reflected
● Output CRC is NOT reflected
● No XOR is performed on the output CRC
Theoretical Concepts:
Important features of a standard CRC are that it:
● Can be used to validate data
● Is reproducible by others
The first feature above is easy to realize in a closed system if corruption of data is infrequent (but
substantial when it occurs). The term "closed system" refers to a situation where the CRC need not be
communicated to others. A correct implementation of a 16-bit CRC will detect a change in a single bit in
a message of over 8000 bytes. An erroneous CRC implementation may not be able to detect such subtle
errors. If errors are usually both rare and large (affecting several bits), then a faulty 16-bit CRC
implementation may still be adequate in a closed system.
The second feature above -- that the CRC is reproducible by others -- is crucial in an open system; that
is, when the CRC must be communicated to others. If the integrity of data passed between two
applications is to be verified using a CRC defined by a particular standard, then the implementation of
that standard must produce the same result in both applications -- otherwise, valid data will be reported
as corrupt.
Reproducibility may be satisfied by even a botched implementation of a standard CRC in most cases --
if everyone uses the same erroneous implementation of the standard. But this approach:
● Modifies the standard in ways that are both unofficial and undocumented.
● Creates confusion when communicating with others who have not adopted the botched
implementation as the implied standard.
The CRC value for the 9-byte reference string, "123456789" is 0xE5CC.
The need to focus on the 16-bit CRC-CCITT (polynomial 0x1021) and not CRC16 (polynomial
0x8005),are as follows :
● Is a straightforward 16-bit CRC implementation in that it doesn't involve:
● reflection of data
● reflection of the final CRC value
● Starts with a non-zero initial value -- leading zero bits can't affect the CRC16 used by LHA,
ARC, etc., because its initial value is zero.
● It requires no additional XOR operation after everything else is done. The CRC32
implementation used by Ethernet, Pkzip, etc., requires this operation; less common 16-bit CRCs
may require it as well.
The need to use a 16-bit CRC instead of a 32-bit CRC is as follows :
● Can be calculated faster than a 32-bit CRC.
● Requires less space than a 32-bit CRC for storage, display or printing.
● Is usually long enough if the data being safeguarded is fewer than several thousand bytes in
length, e.g., individual records in a database.
Example:-
Calculation of the 16-bit CRC-CCITT for a one-byte message consisting of the letter "A":
Quotient= 111100001110111101011001
poly= ------------------------------------------
10001000000100001 ) 1111111111111111010000010000000000000000
10001000000100001
--------------------------- red bits are initial value
11101111110111111 bold bits are message
10001000000100001 blue bits are augmentation
--------------------------
11001111100111100
10001000000100001
-------------------------------
10001111000111010
10001000000100001
---------------- -----------------
00001110000110110
00000000000000000
--------------------------------
00011100001101100
00000000000000000
-------------------------------------
00111000011011000
00000000000000000
-------------------------------------
01110000110110001
00000000000000000
------------------------------------
11100001101100010
10001000000100001
-----------------------------------
11010011010000110
10001000000100001
-----------------------------------
10110110101001110
PROGRAM :
#include<stdio.h>
#include<string.h>
char
data[100],concatdata[117],src_crc[17],dest_crc[17],frame[120],divident[18],divisor[18]="10001000000
100001",res[17]="0000000000000000";
}
else
{
for(i=1;i<=16;i++)
divident[i-1]=divident[i];
}
if(node==0)
divident[i-1]=concatdata[j];
else
divident[i-1]=frame[j];
}
divident[i-1]='\0';
printf("\ncrc is %s\n",divident);
if(node==0)
{
strcpy(src_crc,divident);
}
else
strcpy(dest_crc,divident);
}
int main()
{
int i,len,rest;
printf("\n\t\t\tAT SOURCE NODE\n\nenter the data to be send :");
gets(data);
strcpy(concatdata,data);
strcat(concatdata,"0000000000000000");
for(i=0;i<=16;i++)
divident[i]=concatdata[i];
divident[i+1]='\0';
crc_cal(0);
printf("\ndata is :\t");
puts(data);
printf("\nthe frame transmitted is :\t");
printf("\n%s%s",data,src_crc);
printf("\n\t\tSOURCE NODE TRANSMITTED THE FRAME ---->");
printf("\n\n\n\n\t\t\tAT DESTINATION NODE\nenter the received frame:\t");
gets(frame);
for(i=0;i<=16;i++)
divident[i]=frame[i];
divident[i+1]='\0';
crc_cal(1);
if(strcmp(dest_crc,res)==0)
OUTPUT : RUN 1:
$ cc prog1.c
$ ./a.out
AT SOURCE NODE
enter the data to be send :110011
crc is 0000011000110000
data is : 110011
the frame transmitted is :
1100110000011000110000
crc is 0000000000000000
RUN 2:
AT SOURCE NODE
enter the data to be send :110011
crc is 0000011000110000
data is : 110011
the frame transmitted is :
1100110000011000110000
8. Write a program for distance vector algorithm to find suitable path for transmission.
One of the most popular & dynamic routing algorithms, the distance vector routing algorithms
operate by using the concept of each router having to maintain a table( ie., a vector ), that lets the router
know the best or shortest distance to each destination and the next hop to get to there. Also know as
Bellman Ford(1957) and Ford Fulkerson (1962). It was the original ARPANET algorithm.
Algorithm Overview:
Each router maintains a table containing entries for and indexed by each other router in the
subnet. Table contains two parts :
The metric used here is the transmission delay to each destination. This metric maybe number of hops,
queue length, etc.
The router is assumed to know the distance metric to each of its neighbours.Across the network the
delay is calculated by sending echo packets to each of neighbours.
PROGRAM :
#include<stdio.h>
struct rtable
{
int dist[20],nextnode[20];
}table[20];
int cost[10][10],n;
void distvector()
{
int i,j,k,count=0;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
table[i].dist[j]=cost[i][j];
table[i].nextnode[j]=j;
}
}
do
{
count=0;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
for(k=0;k<n;k++)
{
if(table[i].dist[j]>cost[i][k]+table[k].dist[j])
{
table[i].dist[j]=table[i].dist[k]+table[k].dist[j];
table[i].nextnode[j]=k;
count++;
}
}
}
}
}while(count!=0);
}
int main()
{
int i,j;
printf("\nenter the no of vertices:\t");
scanf("%d",&n);
printf("\nenter the cost matrix\n");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&cost[i][j]);
distvector();
for(i=0;i<n;i++)
{
printf("\nstate value for router %c \n",i+65);
printf("\ndestnode\tnextnode\tdistance\n");
for(j=0;j<n;j++)
{
if(table[i].dist[j]==99)
printf("%c\t\t-\t\tinfinite\n",j+65);
else
printf("%c\t\t%c\t\t%d\n",j+65,table[i].nextnode[j]+65,table[i].dist[j]);
} }
return 0;
OUTPUT :
$ cc prog3.c
$ ./a.out
enter the no of vertices: 6
enter the cost matrix
0 2 1 99 99 1
2 0 99 2 1 99
1 99 0 99 2 2
99 2 99 0 1 5
99 1 2 1 0 99
1 99 2 5 99 0
E E 2
F F 2
9. Using TCP/IP sockets, write a client-server program to make client sending the file name and
the server to send back the contents of the requested file if present.
i. OVERVIEW
Unix sockets is just like two way FIFO's. All data communication will take place through the
socket's interface, instead of through the file interface. Although unix socket's are a special file in the file
system(just like FIFO's), there's usage of socket(), bind(), recv(),etc and not open(), read().
When programming with socket's, usually there's creation of server and client programs. The
server will sit listening for incoming connections from clients and handling. This is similar to the
situation that exists with internet sockets but with fine differences.
For instance, when describing which unix socket that has to be used(i.e the path to the special
file that is the socket). The structure “struct sockaddr_un” has the following fields:
struct sockaddr_un{
unsigned short sa_family; // Address family,AF_XXXX
char sa_data; // 14 bytes of protocol address
};
This is the structure you will be passing to the bind() function, which associates a socket
descriptor(a file descriptor) with a certain file(the name for which is in the sun_path field).
The structure “struct sockaddr_in” is used when we need IP address and Port number to be binded to the
Sockets. It has following fields:
struct sockaddr_in {
short int sin_family; // Address family
unsigned short int sin_port; // Port number
struct in_addr sin_addr; // Internet address
unsigned char sin_zero[8] // Same size as struct sockaddr
};
// Internet adress
struct in_addr {
unsigned long s_addr; // 32 bits or 4 bytes long
};
ii. BACKGROUND REQUIRED:
Most interprocess communication uses the client server model. These terms refer to the two
processes which will be communication with each other. One of the two processes , the client , connects
to the other process, the server, typiceally to make a request for information. A good analogy is a person
who makes a phone call to another person.
Notice that the client needs to know of the existence of and the address of the server, but the
server does not need to know the adresss of(or even the existence of) the client prior to the connection
being established. Notice also that once a connection is established, both sides can send and receive
information.
The system calls for establishing a connection are somewhat different for the client and the
server, but both involve the basic construct of a socket. A socket is one end of an interprocess
communication channel. The two processes each establish their own socket.
The steps involved in establishing a socket on the client side are as follows-
1. Create a socket with the socket() system call .
2. Connect the socket to the address of the server using the connect() system call.
3. Send and receive data.There are a number of ways to do this, but the simplest is to use the
read() and write() systen calls.
The stepd involved in establishing a socket on the server side are as follows-
1. Create a socket with the socket() system call.
2. Bind the socket to an address using the bind() system call. For a server socket on the internet,an
address consists of a port number on the host machine.
3. Listen for connections with the listen() system call.
4. Acept a connection with the accept() system call. This call typically blocks until a client
connects with the server.
5. Send and receive the data.
Socket Types:
When a socket is created, the program has to specify the address domain and the socket type.
Two processes can communicate with each other only if their sockets are of the same type and in the
same domain, in which two processes running on any two hosts on the Internet communicate. Each of
these has it's own adress format.
The address of a socket in the Unix domain is a character string which is basically an entry in the
file system.
The address of a socket in the Internet domain consists of the Internet address of the host
machine (every computer on the Internet has a unique 32 bit address, often reffered to as it's IP address).
In addition , each socket needs a port number on that host. Port numbers are 16 bit unsigned integers.
The lower numbers are reserved in Unix for standard services. For eg, the port number for the FTP
server is 21.
There are two widely used socket types, stream sockets , and datgram sockets. Stream sockets
treat communications as a continuous stream of characters, while datagram sockets have to read entire
messages at once. Each uses it's own communications protocol. Stream sockets use TCP , which is a
reliable , stream oriented protocol, and datagram sockets use UDP, which is unreliable and message
oriented.
2. getservbyname – given service name and protocol , returns a structure which specifies its name(s)
and its port address.
The socket utility functions are as follows:-
1. htons/ntohl- convert short/long from host byte order to network byte order.
2. inet_ntoa/inet_addr- converts 32 bit IP address (network byte order to/from a dotted decimal string)
The header files used in order are:-
1.<sys/types.h> -prerequisite typedefs.
2. <errno.h> -names for “erno” values (error numbers)
3. <sys/socket.> - struct sock addr ;system prototypes and constants .
4. <netdb.h.h> - network info lookup prototypes and structures.
5. <netinet/in.h> - struct sockaddr_in; byte ordering macros.
6. <arpa/inet.h> - utility function prototypes.
PROGRAM :
CLIENT :
#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<netdb.h>
#include<string.h>
printf("\nclient online");
server=gethostbyname(argv[1]);
if(server==NULL)
{
fprintf(stderr,"error ,no such host");
exit(0);
}
printf("\n server online");
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_in*)&serv_addr,sizeof(serv_addr))<0)
error("error writing to socket");
printf("\nclient:enter path with filename:\n");
scanf("%s",filepath);
n=write(sockfd,filepath,strlen(filepath));
if(n<0)
error("\nerror writing to socket");
bzero(buf,3000);
n=read(sockfd,buf,2999);
if(n<0)
error("\nerror reading to socket");
printf("\nclient:displaying from socket");
fputs(buf,stdout);
return 0;
}
SERVER :
#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
exit(1);
}
if(argc < 2)
{
fprintf(stderr,"ERROR,no port provided\n");
exit(1);
}
sockfd=socket(AF_INET,SOCK_STREAM,0);
if(sockfd<0)
error("ERROR opening socket");
bzero((char*) &serv_addr,sizeof(serv_addr));
portno=atoi(argv[1]);
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)
error("ERROR on binding");
listen(sockfd,5);
clilen=sizeof(cli_addr);
printf("SERVER:Waiting for client....\n");
newsockfd=accept(sockfd,(struct sockaddr*) &cli_addr,&clilen);
if(newsockfd<0)
error("ERROR on accept");
bzero(buffer,256);
n=read(newsockfd,buffer,255);
if(n<0)
error("ERROR reading from socket");
printf("SERVER:%s \n",buffer);
if((fd=freopen(buffer,"r",stdin))!=NULL)
{
printf("SERVER:%s found! \n Transfering the contents ...\n",buffer);
while((ch=getc(stdin))!=EOF)
c[i++]=ch;
c[i]='\0';
printf("File content %s\n",c);
n=write(newsockfd,c,1999);
if(n<0)
error("ERROR in writing to socket");
}
else
{
printf("SERVER:File not found!\n");
n=write(newsockfd,"File not found!",15);
if(n<0)
error("ERROR writing to socket");
}
return 0;
}
$ cc prog4c.c
$ ./a.out 127.0.0.1 7000
client online
server online
client:enter path with filename:
hsr.c
10. Implement the above program using as message queues of FIFOs as IPC channel.
FIFO's is used to send data between a Client and Server. If we have a server that is contacted by
numerous clients, each client can write its request to a well-known(i.e, the pathname is known by all
clients) FIFO that the server creates. The figure below shows this arrangement. Since there are multiple
writers for the FIFO, the requests sent by the clients to the server need to be less than PIPE_BUF bytes
in size. This prevents any interleaving of the client writes.
The problem in using FIFO's for this type of client-server communication is how to send replies
back from the server to each client. A single FIFO can't be used, as the clients would never know when
to read their response, versus responses for other clients. One solution is for each client to send its
process ID with the request. The server then creates a unique FIFO for each client, using a pathname
based on the client's process ID.
Server
Wellknown
Clientspecific Clientspecific
FIFO
FIFO FIFO
Client Client
iii. ALGORITHM: There are two programs- Server side & Client side.
Server side:
1. Create a well-known FIFO using “mknod” command.
Ex: mknod(<fifo name>, S_IFIFO | 0666 , 0)
2. Open the above FIFO in readonly mode to accept requests from the clients.
3. When the client opens the other end of FIFO in writeonly mode then read the contents
and store the request(pathname of file) in a buffer.
4. Now create another FIFO(client-specific) in writeonly mode to send the reply(contents of
the file requested)
5. Open the file requested by client and write the contents into the client-speicfic FIFO and
terminate the connection.
Client side:
1. Open the well-known Server FIFO in write mode.
2. Write the pathname of file into this FIFO and send as a request.
3. Now open the Client-specific FIFO in read mode and wait for reply from server.
4. When the contents of file are available on this FIFO display it on the terminal.
PROGRAM :
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>
int main()
{
char p[100],f[100],c[3000];
int num,num2,f1,fd,fd2;
mknod(FIFO1_NAME,S_IFIFO|0666,0);
mknod(FIFO2_NAME,S_IFIFO|0666,0);
printf("\n waiting for server...\n");
fd=open(FIFO1_NAME,O_WRONLY);
printf("\n SERVER ONLINE !\n CLIENT:Enter the path\n");
while(gets(p),!feof(stdin))
{
if((num=write(fd,p,strlen(p)))==-1)
perror("write error\n");
else
{
printf("Waiting for reply....\n");
fd2=open(FIFO2_NAME,O_RDONLY);
if((num2=read(fd2,c,3000))==-1)
perror("Transfer error!\n");
else
{
printf("File recieved! displaying the contents:\n");
if(fputs(c,stdout)==EOF)
perror("print error\n");
exit(1);
}
}
}
}
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[300],ch;
int num,num2,f1,fd,fd2,i=0;
mknod(FIFO1_NAME,S_IFIFO |0666,0);
mknod(FIFO2_NAME,S_IFIFO |0666,0);
printf("\nSERVER ONLINE");
fd=open(FIFO1_NAME,O_RDONLY);
printf("client online\nwaiting for request\n\n");
while(1)
{
if((num=read(fd,p,100))==-1)
perror("\nread error");
else
{
p[num]='\0';
if((f1=open(p,O_RDONLY))<0)
{
printf("\nserver: %s not found",p);
exit(1);
}
else
{
printf("\nserver:%s found \ntranfering the contents",p);
stdin=fdopen(f1,"r");
while((ch=getc(stdin))!=EOF)
c[i++]=ch;
c[i]='\0';
printf("\nfile contents %s\n ",c);
fd2=open(FIFO2_NAME,O_WRONLY);
if(num2=write(fd2,c,strlen(c))==-1)
perror("\ntranfer error");
else
printf("\nserver :tranfer completed");
}
exit(1);
}
}
}
OUTPUT : AT TERMINAL 1:
$ cc prog5s.c
$ ./a.out
server:hsr.c found
tranfering the contents
file contents #include<stdio.h>
int main()
{
printf("\nascii of a %d",'h');
return 1;
}
AT TERMINAL 2:
$ cc prog5c.c
$ ./a.out
SERVER ONLINE !
CLIENT:Enter the path
hsr.c
Waiting for reply....
File recieved! displaying the contents:
#include<stdio.h>
int main()
{
printf("\nascii of a %d",'h');
return 1;
}
11. Write a program for simple RSA algorithm to encrypt and decrypt the data.
RSA ALGORITHM :
The RSA Public key algorithm was invented in 1977 by Ron Rivest, Adi Shamir and Leonard Adleman
(RSA). The algorithm Supports Encryption and Digital Signatures. It is the most widely used public key
algorithm. RSA gets its security from the integer factorization problem. The algorithm is relatively easy
to understand and implement. It has been patent free since 2000. RSA is used in security protocols such
as IPSEC/IKE -IP data security,TLS/SSL -transport data security (web), PGP -email security,SSH
-terminal connection security,SILC -conferencing service security.
Theoretical Concepts:
RSA gets its security from the factorization problem. The difficulty of factoring large numbers is
the basis of security of RSA.
Factorization algorithms can be used to factor faster than brute forcing. Some of them are Trial division,
Pollard's rho, Pollard's p-1, Quadratic sieve, elliptic curve factorization, Random square factoring,
Number field sieve, etc.
A Prime number is a positive integer and is divisible only by itself and 1. Prime numbers are found with
primality testing; an algorithm which tests a probable prime for primality. If primality testing returns
false prime numbers the cryptographic algorithm may be insecure (or will not function correctly).
RSA depends on prime numbers in key generation. It also uses �strong� primes, numbers whose
factors of the prime are also primes.
Key generation:
2)Compute modulus n = pq
The selected public exponent e, which is used as public key with n. It is used to encrypt
messages and to verify digital signatures. The e is stored for later with n. The e is usually small number
but it can be 1 < e < phi . The e must be relatively prime to phi , hence gcd(e, phi ) = 1.(gcd = greatest
common divisor, using the Euclidean algorithm)
The private exponent d, is the actual RSA private key. The d must not be disclosed at any time
or the security of the RSA is compromised. The d is found by computing the multiplicative inverse d =
e^-1 mod phi . The extended Euclidean algorithm is commonly used to compute inverses. The d
exponent is used to decrypt messages and to compute digital signatures. Implementations try to find as
small d as possible to make decryption faster. This is fine as long as it is assured that d is about the same
size as n. If it is only one quarter of size it is not considered safe to be used. It is possible to find a
smaller d by using lcm(p-1,q-1) instead of phi (lcm = least common multiple, lcm(p-1,q-1) = phi /gcd(p-
1,q-1) ).
PROGRAM :
#include<stdio.h>
#include<math.h>
int main()
{
long a,b,n,x,y,i,j,temp;
char ciper[20],decrp[20];
char text[20];
printf("\n enter prime no.1:\t");
scanf("%d",&a);
printf("\n enter prime no.2:\t");
scanf("%d",&b);
n=a*b;
temp=(a-1)*(b-1);
for(i=2;i<temp;i++)
{
if(gcd(temp,i)==1)
{
x=i;
break;
}
}
printf("\nthe value of public key is {%d , %d}",x,n);
for(j=2;j<temp;j++)
{
if(((j*x)%temp)==1)
{
y=j;
break;
}
}
printf("\nthe value of private key is {%d , %d}",y,n);
printf("\nenter the plain text:");
scanf("%s",text);
i=0;
printf("\ncipher text is:\t");
while(text[i]!='\0')
{
ciper[i]=cal(text[i]-97,x,n);
printf("%c ",ciper[i]+97);
decrp[i]=cal(ciper[i],y,n)+97;
i++;
}
printf("\n the received text is %s",decrp);
return 0;
}
OUTPUT : RUN 1:
$ ./a.out
enter prime no.1: 5
enter prime no.2: 11
the value of public key is {3 , 55}
the value of private key is {27 , 55}
enter the plain text:revaitm
RUN 2:
enter prime no.1: 7
enter prime no.2: 5
12. Write a program for Congestion control using the leaky bucket algorithm.
The leaky-bucket implementation is used to control the rate at which traffic is sent to the
network. A leaky bucket provides a mechanism by which bursty traffic can be shaped to present a steady
stream of traffic to the network, as opposed to traffic with erratic bursts of low-volume and high-volume
flows.
Traffic analogy An appropriate analogy for the leaky bucket is a scenario in which four lanes of
automobile traffic converge into a single lane. A regulated admission interval into the single lane of
traffic flow helps the traffic move. The benefit of this approach is that traffic flow into the major arteries
(the network) is predictable and controlled. The major liability is that when the volume of traffic is
vastly greater than the bucket size, in conjunction with the drainage-time interval, traffic backs up in the
bucket beyond bucket capacity and is discarded.
● The bucket can queue at most b bytes. If a packet arrives when the bucket is full, the packet is
discarded.
● Packets drain through the hole in the bucket, into the network, at a constant rate of r bytes per
second, thus smoothing traffic bursts.
The size b of the bucket is limited by the available memory of the system.
Sometimes the leaky bucket and token algorithms are lumped together under the same name.
PROGRAM :
#include<stdio.h>
#include<stdlib.h>
int trand(int a)
{
int rn;
rn=random()%10;
rn=rn%a;
if(rn==0)
rn=1;
return(rn);
}
int main()
{
int i,packet[5],psz,bsz,pszrn=0,clk,ptime,premain,orate,flag=0;
for(i=0;i<5;i++)
packet[i]=trand(6)*10;
printf("\nenter the o/p rate");
scanf("%d",&orate);
printf("\nenter the bucket size");
scanf("%d",&bsz);
for(i=0;i<5;i++)
{
if((packet[i]+pszrn)>bsz)
printf("\n incoming packet size %d is greater than bucket size_reject",packet[i]);
else
{
for(;;)
{
premain=4-i;
psz=packet[i];
pszrn+=psz;
printf("\nincoming packet size is %d",psz);
printf("\n no.of packets waiting for transmission= %d",pszrn);
ptime=trand(4)*10;
printf("\nnext packet will come at %d",ptime);
for(clk=0;clk<=ptime;clk++)
{
printf("\ntime left =%d",ptime-clk);
sleep(1);
if(pszrn)
{
if(pszrn==0)
printf("\nbucket is empty");
else
{
if(pszrn>=orate)
printf("%d bytes are tranmited",orate);
else
printf("\n %d bytes are transmitted",pszrn);
}
if(pszrn<=orate)
pszrn=0;
else
pszrn-=orate;
printf("\nbytes remaining %d ",pszrn);
}
else
printf("\nbytes remaing %d ",pszrn);
}
if(pszrn!=0)
flag=1;
break;
}
}
}
printf("\n\n");
return 0;
}
OUTPUT : RUN 1:
$ cc prog8.c
$ ./a.out
enter the o/p rate10
enter the bucket size5
RUN 2:
Viva Questions
1. What are functions of different layers?
2. Differentiate between TCP/IP Layers and OSI Layers
3. Why header is required?
4. What is the use of adding header and trailer to frames?
5. What is encapsulation?
6. Why fragmentation requires?
7. What is MTU?
8. Which layer imposes MTU?
9. Differentiate between flow control and congestion control.
10. Differentiate between PointtoPoint Connection and EndtoEnd connections.
11. What are protocols running in different layers?
12. What is Protocol Stack?
13. Differentiate between TCP and UDP.
14. Differentiate between Connectionless and connection oriented connection.
15. Why frame sorting is required?
16. What is meant by subnet?
17. What is meant by Gateway?
18. What is an IP address?
19. What is MAC address?
20. Why IP address is required when we have MAC address?
21. What is meant by port?
22. What are ephemerical port number and well known port numbers?
23. What is a socket?
24. What are the parameters of socket()?
25. Describe bind(), listen(), accept(),connect(), send() and recv().
26. What are system calls? Mention few of them.
27. What is IPC? Name three techniques.
28. Explain mkfifo(), open(), close() with parameters.
29. What is meant by file descriptor?
30. What is meant by traffic shaping?
31. How do you classify congestion control algorithms?
32. Differentiate between Leaky bucket and Token bucket.
33. How do you implement Leaky bucket?
34. How do you generate busty traffic?
35. What is the polynomial used in CRCCCITT?
36. What are the other error detection algorithms?
37. What is difference between CRC and Hamming code?
38. Why Hamming code is called 7,4 code?
39. What is odd parity and even parity?
40. What is meant by syndrome?
41. What is generator matrix?
42. What is spanning tree?
43. Where Pirm’s algorithm does finds its use in Networks?
44. Differentiate between Prim’s and Kruskal’s algorithm.
45. What are Routing algorithms?
46. How do you classify routing algorithms? Give examples for each.
47. What are drawbacks in distance vector algorithm?
48. How routers update distances to each of its neighbor?
49. How do you overcome count to infinity problem?
50. What is cryptography?
51. How do you classify cryptographic algorithms?
52. What is public key?
53. What is private key?
54. What are key, ciphertext and plaintext?
55. What is simulation?
56. What are advantages of simulation?
57. Differentiate between Simulation and Emulation.
58. What is meant by router?
59. What is meant by bridge?
60. What is meant by switch?
61. What is meant by hub?
62. Differentiate between route, bridge, switch and hub.
63. What is ping and telnet?
64. What is FTP?
65. What is BER?
66. What is meant by congestion window?
67. What is BSS?
68. What is incoming throughput and outgoing throughput?
69. What is collision?
70. How do you generate multiple traffics across different senderreceiver pairs?
71. How do you setup Ethernet LAN?
72. What is meant by mobile host?
73. What is meant by NCTUns?
74. What are dispatcher, coordinator and nctunsclient?
75. Name few other Network simulators
76. Differentiate between logical and physical address.
77. Which address gets affected if a system moves from one place to another place?
78. What is ICMP? What are uses of ICMP? Name few.
79. Which layer implements security for data?