Documente Academic
Documente Profesional
Documente Cultură
of CSE
Experiment 1
Simulate a three nodes point to point networks with a duplex links between them. Set the queue size and vary the bandwidth and find the number of packets dropped. The topology is shown below :
HUB
H 1
STEPS:
H 2
1) Select the hub icon on the toolbar and drag it onto the working window. 2) Select the host icon on the toolbar and drag it onto the working window. Repeat this for another host icon. 3) Select the link icon on the toolbar and drag it on the screen from the host to the hub and again from host to the hub. Here the hub acts as node 3 in the point-topoint network. This leads to the creation of the 3-node point-to-point network topology. Save this topology as a .tpl file. 4) Double-click on the host; 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-Select FIFO and set the queue size to 50 and press OK. Then click on Add. Another dialog box pops up. Click on the Command box and type the Command as follows: stg u 1024 100 1.0.1.2 and click OK. 5) Double-click on host, and follow the same step as above with only change in command as follows: rtg u w log1 6) Double click on the link between node 1 and the hub to set the bandwidth to some
DSCE, Bangalore
Dept. of CSE NETWORK PROGRAMMING LAB MANUAL initial value say 10 Mbps. Repeat with the other node. 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 server can run/pause/continue/stop/ abort/ disconnect/ reconnect/submit asimulation.No simulation settings can be changed in this mode. 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. 9) To start the playback, the user can left-click the start icon (| >) of the time bar located at the bottom. Tb animation player will then start playing the recorded packet animation. 10) Change the bandwidth say, 9Mbps, and run the simulation and compare the two results. 11) To view the results, go to the filename .results folder. The screenshot below explain the topology.
DSCE, Bangalore
Dept. of CSE
Dept. of CSE NETWORK PROGRAMMING LAB MANUAL Results: By setting the bandwidth as 10 Mbps on both the links and queue size as 50 we obtain the following results: Output throughput n1-p1 =1190 Input throughput n3-p1=1190 Collision and drop =0 By changing bandwidth to 9Mbps in the destination link,we obtain the following results: Output throughput n1-p1 =1190 Input throughput n3-p1=varying Collision and drop =-0
DSCE, Bangalore
Dept. of CSE
Experiment 2
Simulate a four node point to point network and connect the link as follows : Apply a TCP agent between n1 and n3 and apply a UDP agent between n2 and n3. Apply relevant applications over TCP and UDP agents changing the parameters and determine the number of packets sent by the two agents. The topology is shown below:
HUB
N3
N2
STEPS: 1) Create the topology as specified in the question, in the draw mode of the simulator. 2) Go to edit mode and save the topology. 3) Setup a TCP connection between node 1 and node 3 using the following commands: stcp[-p port][-l writesize] host1Paddr rtcp[-p port][-l readsize] 4) Setup a UDP connection between node 2 and node 3 using the following commands: stg[-u payload size duration][Hostaddress] rtg[-u][-w log]
5)
Set the output throughput log to determine the number of packets sent by TCP/UDP as described in experment1.
DSCE, Bangalore
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 Results: 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
DSCE, Bangalore
Dept. of CSE
DSCE, Bangalore
Dept. of CSE
Experiment 3
Simulate the different types of Internet traffic such as FTP, TELNET over a network and analyze the throughput. The topology is shown below:
N1 STEPS:
1) Create a topology of four nodes; connect these nodes to a hub. 2) Go to the edit mode and setup FTP traffic node1 and node4 using the port number 23. 3) Set the input and output through put log file as described in the above experiments. 4) To view the results, go to the filename.results folder. To setup a TELNET CONNECTION: 1) Create a topology of four nodes, connect these nodes to a hub. 2) Go to the edit mode and setup a TELNET traffic between node1 node4 using the port number 7300. 3) Set the input and output through put log file as described in the above experiments. 4) To view the results, go to the filename.results folder.
DSCE, Bangalore
Dept. of CSE
DSCE, Bangalore
Results:
FOR TELNET: Command used: Stcp p 7300 l 1024 1.0.1.6 Rtcp -p 7300 l 1024 Results : output throughput n1-p1 = 495-1095 Input throughput n2-p1 = 495-1095
DSCE, Bangalore
10
Dept. of CSE
Experiment 4
Simulate the transmission of ping messages over a network topology consisting of 6 nodes and find the number of packets dropped due to congestion. The topology is shown below:
HOST2
HOST3
HOST7
SWITCH 1
HOST6
1) Click on the subnet icon on the toolbar and then click on the screen of the working window. 2) Select the required number of hosts and a suitable radius between the host and the switch. 3) In the edit mode, get the IP address of one of the hosts say, host1 4) Then for the other host say, host2 set the drop packet and no: of collisions statistics as described in the earlier experiments. 5) Now run the simulation. 6) Now click on any one of the hosts and click on comm. 7) and console 8) Ping the destination node. DSCE, Bangalore 11
Dept. of CSE
EXAMPLE AND RESULTS OF EXPT4 Results: Sender:stcp p 7000 l 1024 1.0.1.4 Receiver:rtcp p 7000 l 1024
Command Console:Goto tools-> simulation time and change Simulation time to 100. During run mode, double click host 2 and then click command console. And execute the following command. ping 1.0.1.4
DSCE, Bangalore
12
Experiment 5
Simulate an Ethernet LAN using N nodes (6-10), change error rate and data rate and compare throughput. The topology is shown below:
SWITCH
HOST
HOST
HOST
HOST
STEPS:
1) Connect one set of hosts with a hub and another set of hosts also through a hub an connect these two hubs through a switch.This forms an Ethernet LAN. 2) Setup a TCP connection between a host on one hub and host on another hub using the following command: stcp [-p port] [-l writesize] hostaddr rtcp [-p port] [-l readsize]
DSCE, Bangalore
13
Dept. of CSE NETWORK PROGRAMMING LAB MANUAL 3) Setup the error rate, data rate in the physical layer, input and output throughput in the mac layer as described above. 4) Change error rate and data rate and compare the throughputs. 5) View the results in the filename.results. The screenshot of the topology is shown below:
DSCE, Bangalore
14
Dept. of CSE
Input Throughput: 654-1091 Changed data rate: 100 Mbps Output Throughput: 1547-9765 Input Throughput: 1547-9765 For 10 nodes: Initial error rate:0.0 Initial data rate: 10 Mbps Output Throughput: 654-1091 Input Throughput: 654-1091 Changed error rate: 1.0 Data rate:10 Mbps Output Throughput: 654-1091 Input Throughput: 654-1091
Experiment 6
Simulate the Ethernet LAN using N nodes and set multiple traffic nodes and determine collisions across different nodes. The topology is shown below:
DSCE, Bangalore
16
Dept. of CSE
HUB HOST
HUB HOST
HOST
HOST
STEPS:
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. 2. Setup multiple traffic connectiona between the host on one hub and hosts on another hub using the following command: stcp [-p port] [-l writesize] hostIPaddr rtcp [-p port] [-l readsize] 3. Setup the collision log at the destination hosts in the MAC layer as described in the earlier experiments. 4. View the results in the filename.results.
DSCE, Bangalore
17
Dept. of CSE
stcp p 7000 -1 1024 1.0.1.6 stcp p 7001 -1 1024 1.0.1.6 rtcp p 7001 -1 1024 Results: Drops at node 5: Drops at node 4: 324-750 274-930
DSCE, Bangalore
19
Dept. of CSE
Experiment 7
Simulate an Ethernet LAN using N nodes and set multiple traffic nodes and plot congestion window for different source/destination. The topology is shown below:
Host1
Host4
Host2
hub
switch
Host3 STEPS: 1) Connect one set of host with a hub and another set of host also through a hub and connect these two hubs through a switch.This forms an Ethernet LAN. 2) Setup multiple traffic connections between the host on one hub and host on another hub using the following command: stcp [-p port][-l writesize] host1paddr rtcp [-p port][-l readsize] 3) Setup the collision log at the destination host in the MAC layer as describe in the earlier experiments. 4) To plot the congestion window go to Menu->Tools->Plot graph->File->open ->filename.results->filename.coll.log. 5) View the results in the filename.results.
DSCE, Bangalore
20
Dept. of CSE
DSCE, Bangalore
21
Dept. of CSE
DSCE, Bangalore
22
Dept. of CSE
Experiment 8
Simulate simple BSS and with transmitting nodes in wire-less LAN by simulation and determine the performance with respect to transmission of packets. The topology is shown below: Host
Router
WLAN Access point WLAN mobile node STEPS: 1) Connect a host and two WLAN access points to a router. 2) Setup multiple mobile nodes around the two WLAN access points and set the path for each mobile node. 3) Setup a ttcp connection between the mobile nodes and host using the following command: Ttcp r u s[-p port number] 4) Setup the input throughput log at the destination host. 5) To set the transmission range go to Menu->Settings->WLAN mobile node->Show transmission range. 6) View the results in the filename.results. WLAN mobile node
DSCE, Bangalore
23
Dept. of CSE
DSCE, Bangalore
24
Dept. of CSE
both commands
Mark the interference range and transmission range Results: Input Throughput: 1190
DSCE, Bangalore
25
Dept. of CSE
PART B PROGRAM 1
Write a Program in C/ C++ for error detecting code sing CRC-CCITT (16 bit)1,
Theory
It does error checking via polynomial division. In general, a bit string bn-1bn-2bn-3b2b1b0 As bn-1Xn-1 + bn-2 Xn-2 + bn-3 Xn-3 + b2 X2 + b1 X1 + b0 Ex: 10010101110 As X10 + X7 + X5 + X3 + X2 + X1 All computations are done in modulo 2 Algorithm:-
Program
#include<stdio.h> #include<string.h> #define N strlen(g) char t[128], cs[128], g[]="10001000000100001"; int a,e,c; void xor() { for(c=1;c<N;c++) cs[c]=((cs[c]==g[c])?'0':'1'); } void crc() {
DSCE, Bangalore
26
for(e=0;e<N;e++) cs[e]=t[e]; do{ if(cs[0]=='1')xor(); for(c=0;c<N-1;c++) cs[c]=cs[c+1]; cs[c]=t[e++]; }while(e<a+N-1); } void main() { printf("\nenter poly:"); scanf("%s",t); printf("\n generating polynomial is:%s",g); a=strlen(t); for(e=a;e<a+N-1;e++) t[e]='0'; printf("\n modified t[u] is:%s",t); crc(); printf("\n checksum is:%s",cs); for(e=a;e<a+N-1;e++) t[e]=cs[e-a]; printf("\nfinal codeward is:%s",t); printf("\n test error detection 0(yes) 1(no)?:"); scanf("%d",&e); if(e==0){ printf("enter position where error is to inserted:"); scanf("%d",&e); t[e]=(t[e]=='0')?'1':'0'; printf("errorneous data:%s\n",t); } crc(); for(e=0;(e<N-1)&&(cs[e]!='1');e++); if(e<N-1) printf("error detected"); else printf("no error detected"); }
Dept. of CSE
Output
Enter poly : 1011101 Generating Polynomial is : 10001000000100001 Modified t[u] is : 10111010000000000000000 Checksum is : 1000101101011000 Final Codeword is : 10111011000101101011000 Test Error detection 0(yes) 1(no) ? : 0 Enter position where you want to insert error : 3 Errorneous data : 10101011000101101011000 Error detected. Enter poly : 1011101 Generating Polynomial is : 10001000000100001 Modified t[u] is : 10111010000000000000000 Checksum is : 1000101101011000 Final Codeword is : 10111011000101101011000
DSCE, Bangalore
27
Dept. of CSE
PROGRAM 2 Write a Program in C/ C++ for frame sorting techniques used in buffer At the sender, the accepted message is segmented and multiple frames are generated. These frames are sent in order of their sequence number. Frames could arrive in any order at receiver based on the transmission path. Frame sorting is needed at receiver side to reorder the frames and form the message.
Frame format
Different frame formats are used for different applications. For example HDLC frame format is used for Ethernet. In general frames have fields like sequence number, size, data and crc etc Sequence number Size Data
Dept. of CSE NETWORK PROGRAMMING LAB MANUAL for(i=0;i<n-1;i++) { ex = 0; for(j=0;j<n-i-1;j++) if(arr[j].fslno > arr[j+1].fslno) { temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; ex++; } if(ex==0) break; } } int main() { int i; system("clear"); printf("enter the number of frames\n"); scanf("%d",&n); printf("enter the frame sequence number and frame contents\n"); for(i=0; i<n; i++) scanf("%d%s",&arr[i].fslno,&arr[i].finfo); sort(); printf("the frames in sequence\n"); for(i=0;i<n;i++) { printf("01111110 %d\t%s 01111110\n",arr[i].fslno,arr[i].finfo); printf("|------------------------------------------|\n"); } } OUTPUT:Enter the number of frames 5 Enter frame sequence number and frame contents random seq no.=346 enter content aaaa random seq no.=130 enter content bbbb random seq no.=10982 enter content cccc random seq no.=1090 enter content dddd random seq no.=11656 enter content eeee frames in sequence 01111110 130 bbbb 01111110 01111110 346 aaaa 01111110 01111110 1090 dddd 01111110 01111110 10982 cccc 01111110 01111110 11656 eeee 01111110
DSCE, Bangalore
29
Dept. of CSE
PROGRAM 3: Write a Program in C/ C++ for distance vector algorithm to find suitable path for transmission #include<stdio.h> struct network { int dist[10], outgoing[10]; }; struct network nodes[10]; void init(int n) { int i,j; for(i=0;i<n;i++) { for(j=0;j<n;j++) if(i!=j) { nodes[i].dist[j]=999; nodes[i].outgoing[j]=j; } nodes[i].dist[i]=0; nodes[i].outgoing[i]=i; } } void update(int i, int j, int k) { nodes[i].outgoing[j]=k; nodes[i].dist[j]=nodes[i].dist[k]+nodes[k].dist[j]; } void floyd(int n) { int i, j, k; for(k=0;k<n;k++) for(i=0;i<n;i++) for(j=0;j<n;j++) if(nodes[i].dist[j]>(nodes[i].dist[k]+nodes[k].dist[j])) update(i,j,k); } void main() { int n, i, j; printf("enter the num of nodes\n"); scanf("%d",&n); init(n); DSCE, Bangalore 30
Dept. of CSE NETWORK PROGRAMMING LAB MANUAL printf("enter the distances \n"); for(i=0;i<n;i++) for(j=0;j<n;j++) { if(i!=j) { printf("enter distance from %d to %d\n",i+1,j+1); scanf("%d",&nodes[i].dist[j]); } } floyd(n); printf("distance vector routing algorith\n"); for(i=0;i<n;i++) { printf("%d nodes vector table\n",i+1); printf("\t DEST \t DIST \t HOP\n"); for(j=0;j<n;j++) if(i!=j) { printf("\t %d \t %d \t %d\n",j+1,nodes[i].dist[j],nodes[i].outgoing[j]+1); } } }
DSCE, Bangalore
31
Dept. of CSE
PROGRAM 4 Write a Program in C/ C++ for client server communication using TCP or IP sockets to make client send the name of the file and server to send back the contents of the requested file if present. The Berkeley 4BSD series was an almost unbelievable advance in Unix development. Among the features it added were virtual memory, shared memory, and sockets. Sockets were added in 4.2BSD. Conceptually, Internet sockets on a Unix system look like a numbered array of interprocess communication channels -- so there is a socket 0, socket 1, socket 2, and so forth. They are used in a client-server relationship; a daemon wishing to provide a service creates a socket and listens to it; a client program connects to the socket and makes requests. The daemon is also able to send messages back to the client. Creating a Socket The socket system call is given below: s = socket(domain, type, protocol); The domain is either AF_UNIX or AF_INET. An AF_UNIX socket can only be used for interprocess communications on a single system, while an AF_INET socket can be used for communications between systems. The type specifies the characteristics of communication on the socket. SOCK_STREAM creates a socket that will reliably deliver bytes in-order, but does not respect messages boundaries; SOCK_DGRAM creates a socket that does respect message boundaries, but does not guarantee to deliver data reliably, uniquely or in order. A SOCK_STREAM socket corresponds to TCP; a SOCK_DGRAM socket corresponds to UDP The protocol selects a protocol. Ordinarily this is 0, allowing the call to select a protocol. This is almost always the right thing to do, though in some special cases you may want to select the protocol yourself. Remember that this refers to the underlying network protocol: such well-known protocols as http, ftp, and ssh are all built on top of tcp, so tcp is the right choice for any of those protocols. For example: s = socket(AF_INET, SOCK_STREAM, 0); will create a socket that will use TCP to communicate. The return value (s) is a file descriptor for the socket. Binding a Socket At this point created a socket, but name is not given to it. To give a name to the socket by using the bind system call: bind(s, name, namelen);
DSCE, Bangalore
32
Dept. of CSE
This call gives the socket a name. For an Internet socket, the name is a struct defined as struct sockaddr_in { sa_family_t sin_family; /* address family: AF_INET */ u_int16_t sin_port; /* port in network byte order */ struct in_addr sin_addr; /* internet address */ }; /* Internet address. */ struct in_addr { u_int32_t s_addr; /* address in network byte order */ }; sin_family is always AF_INET ; sin_port is the port number, and sin_addr is the IP address. Port numbers below 1024 are reserved - that means only processes with an effective user id of 0 (ie the root) can bind to those ports. Listening to the Socket Once the socket has been created and bound, the daemon needs to indicate that it is ready to listen to it. It does this with the listen system call, as in listen(s, 5); The main thing this does is to set a limit on how many would-be clients can be queued up trying to connect to the socket (the limit in this example is 5). If the limit is exceeded the clients don't actually get refused, instead their connection requests get dumped on the floor. Eventually they will end up retrying. Accepting Connections The server is able to accept connections by calling accept: newsock = accept(s, (struct sockaddr *)&from, &fromlen); For this call, s is, as you'd expect the socket that was returned oh so long ago by the socket call. The accept() call blocks until the client connects to the socket. Connecting to the daemon A client connects to the socket using the connect call. First it creates a socket using the socket call, then it connects it to the daemon's socket using connect : connect(s, (struct sockaddr *)&server, sizeof(server)); This call returns a new socket. This means the daemon can communicate with the client using the newly created (and unnamed) socket, while continuing to listen on the old one. At this point, the server normally forks a child process to handle the client, and goes back to its accept loop. DSCE, Bangalore 33
Dept. of CSE
The child doing the communication can either use standard read and write calls, or it can use send and recv. These calls work like read and write, except that you can also pass flags allowing for some options.
Sending Data
There are a variety of functions that may be used to send outgoing messages. may be used in exactly the same way as it is used to write to files. This call may only be used with SOCK_STREAM type sockets.
write()
#include<sys/types.h> #include<sys/socket.h> int write(int fd, char *msg, int len); fd is the socket descriptor. msg specifies the buffer holding the text of the message, and len specifies the length of the message. is similar to write() except that it writes from a set of buffers. This is called a gather write. This call may only be used with SOCK_STREAM type sockets.
writev() send() may be used in the same way as write(). The prototype is
#include<sys/types.h> #include<sys/socket.h> int send(int fd, char *msg, int len, int flags); fd is the socket descriptor. msg specifies the buffer holding the text of the message, and len specifies the length of the message. flags may be formed by ORing MSG_OOB and MSG_DONTROUTE. The latter is only useful for debugging. This call may only be used with SOCK_STREAM type sockets. Receiving Data There are a variety of functions that may be used to receive incoming messages. may be used in the exactly the same way as for reading from files. There are some complications with non-blocking reads. This call may only be used with SOCK_STREAM type sockets.
read()
#include <sys/types.h> #include <sys/socket.h> int read(int fd, char *buff, int len) fd is the socket descriptor. buff is the address of a buffer area. len is the size of the buffer. DSCE, Bangalore 34
Dept. of CSE
readv()
may be used in the same way as read() to read into several separate buffers. This is called a scatter read. This call may only be used with SOCK_STREAM type sockets.
recv() may be used in the same way as read(). The prototype is
#include <sys/types.h> #include <sys/socket.h> int recv(int s, char *buff, int len, int flags) buff is the address of a buffer area. len is the size of the buffer. flags is formed by ORing MSG_OOB and MSG_PEEK allowing receipt of out of band data and allowing peeking at the incoming data. This call may only be used with SOCK_STREAM type sockets.
DSCE, Bangalore
35
Dept. of CSE NETWORK PROGRAMMING LAB MANUAL #include<stdio.h> #include<sys/types.h> #include<sys/socket.h> #include<netinet/in.h> #include<fcntl.h> int main(int argc,char **argv) { int sockfd,newsockfd,portno=7000,clienlen; char filename[256],c[2000]; struct sockaddr_in serv_addr,clin_addr; int fd; printf("Enter the port number: \n"); scanf("%d",&portno); sockfd=socket(AF_INET,SOCK_STREAM,0); 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); bind(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)); listen(sockfd,5); printf("server waiting for client\n"); clienlen=sizeof(clin_addr); newsockfd=accept(sockfd,(struct sockaddr *)&serv_addr,&clienlen); bzero(filename,256); read(newsockfd,filename,255); fd=open(filename,O_RDONLY,0); read(fd,c,1999); send(newsockfd,c,1999,0); close(newsockfd); return 0; } CLIENT: #include<stdio.h> #include<sys/types.h> #include<sys/socket.h> #include<netinet/in.h> int main(int argc,char **argv) { int sockfd,portno; struct sockaddr_in serv_addr; char filename[256],c[2000]; printf("Enter the port number: \n"); scanf("%d",&portno); sockfd=socket(AF_INET,SOCK_STREAM,0); DSCE, Bangalore 36
Dept. of CSE NETWORK PROGRAMMING LAB MANUAL bzero((char *)&serv_addr,sizeof(serv_addr)); serv_addr.sin_family=AF_INET; serv_addr.sin_port=htons(portno); serv_addr.sin_addr.s_addr=inet_addr(argv[1]); connect(sockfd,(struct sockaddr*)&serv_addr,sizeof(serv_addr)); printf("enter path with filename\n"); scanf("%s",filename); write(sockfd,filename,255); bzero(c,2000); recv(sockfd,c,1999,0); printf("received:\n%s ",c); close(sockfd); return 0; }
output
steps:1) Open two different terminals(one for server and another for client.) 2) enter the following command in server side terminal #cc server.c -o ser #./ser Enter the port no: 3000 Server waiting for client. 3) Enter the following command in client side terminal #cc client.c -o cli #./cli 127.0.0.1 Enter the port no: 3000 Enter the path of the filename to be transmitted sample.txt received: PROGRAM 5 Write a Program in C/ C++ for client server communication using message queues or FIFO as IPC channels to make client send the name of the file and server to send back the contents of the requested file if present. FIFOs allow two unrelated processes to communicate with each other. They are also known as named pipes and can be used to establish a one-way (half-duplex) flow of data. Named pipes are identified by a file kept on the file system. Because FIFOs have the pathname of a file associated with them, it is possible for unrelated processes to communicate with each other. Two unrelated processes can open the file associated with
DSCE, Bangalore
37
Dept. of CSE NETWORK PROGRAMMING LAB MANUAL the FIFO and begin communication. FIFOs are file system-persistent objects, that is, they exist beyond the life of the process. They have to be explicitly deleted by one of the processes by calling "unlink" or else deleted from the file system via the command line.
Dept. of CSE NETWORK PROGRAMMING LAB MANUAL one direction. However, you have to be very careful about the order in which these FIFOs are opened in the client and server, otherwise a deadlock may occur.
Benefits of FIFO
FIFOs are very simple to use. mkfifo is a thread-safe function. No synchronization mechanism is needed when using FIFOs. Write (using write function call) to a FIFO is guaranteed to be atomic. It is atomic even if the FIFO is opened in non-blocking mode. FIFOs have permissions (read and write) associated with them, unlike anonymous pipes. These permissions can be used to enforce secure communication. Limitations of FIFOs FIFOs can only be used for communication among processes on the same host machine. FIFOs can be created only in the local file system of the host, that is, you cannot create a FIFOs e on the NFS file system. Due to their basic blocking nature of pipes, careful programming is required for the client and server, in order to avoid deadlocks. FIFO data is a byte stream, and no record identification exists.
DSCE, Bangalore
Dept. of CSE NETWORK PROGRAMMING LAB MANUAL 9) close(sfd) 10) close(cfd) CLIENT #include<fcntl.h> #include<unistd.h> #include<sys/types.h> #include<sys/stat.h> #include<stdio.h> #define fifo1 "/root/fifox" #define fifo2 "/root/fifoy" int main() { char filename[100],c[2000]; int fd1,fd2; int num; mknod(fifo1,S_IFIFO |0777,0); mknod(fifo2,S_IFIFO |0777,0); printf("client online\n"); fd1=open(fifo1,O_WRONLY,0); printf("enter file name\n"); scanf("%s",filename); write(fd1,filename,100); fd2=open(fifo2,O_RDONLY); while((num=read(fd2,c,1999))<0); printf("%s",c); return 0; } SERVER: #include<fcntl.h> #include<unistd.h> #include<sys/types.h> #include<sys/stat.h> #include<stdio.h> #define fifo1 "/root/fifox" #define fifo2 "/root/fifoy" int main() { char filename[100],c[2000]; int fd1,fd2,fd; int num; mknod(fifo1,S_IFIFO |0777,0); mknod(fifo2,S_IFIFO |0777,0); printf("server online\n"); fd1=open(fifo1,O_RDONLY); printf("waiting for request\n"); while((num=read(fd1,filename,100))<0); DSCE, Bangalore 40
Dept. of CSE
output
steps:1) Open two different terminals(one for server and another for client.) 2) enter the following command in server side terminal #cc server.c -o fifoser #./fifoser Server online server waiting for Request. Sample.txt transmitting data. 3) Enter the following command in client side terminal #cc client.c -o fifocli #./fifocli 127.0.0.1 Enter the path of the filename to be transmitted sample.txt received:
PROGRAM 6 Write a Program in C/ C++ for simple RSA algorithm to encrypt and decrypt the data The RSA algorithm is named after Ron Rivest, Adi Shamir and Len Adleman, who invented it in 1977. 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.
Dept. of CSE NETWORK PROGRAMMING LAB MANUAL 4. Compute the secret exponent d, 1 < d < (n), such that ed 1 mod (n). 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:1. 2. 3. 4. Obtains the recipient B's public key (n, e). Represents the plaintext message as a positive integer m. Computes the ciphertext c = m^e mod n. 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.
Notes on Implementation
Example to encrypt message with ASCII characters: n = 253, d = 17 and e = 13 Instead of encrypting the whole message, encrypt ASCII value of each character in the message. Instead of using pow(a, b) % n, devise a multiplication-modulo routine as given below: Mult_mod(unsigned int a, unsigned int b, unsigned int n) { int I; unsigned long int k; for (I=1; I<=b; I++) k = (k * a ) % n; return k; }
Program for simple RSA algorithm to encrypt and decrypt the data. #include<stdio.h> #include<stdlib.h> #include<string.h> unsigned int mod_exp(int base,int exp,int n) { unsigned int i,pow=1; DSCE, Bangalore 42
Dept. of CSE for(i=0;i<exp;i++) pow=(pow*base)%n; return pow; } int gcd(int m,int n) { while(m!=n) { if(m==n || n==1) { m=1,n=1; break; } else { if(m>n) m=m-n; else n=n-m; } } return m; } int main() { int p=23,q=11; int n=p*q; int d=1,e=n-1,i,j; char in[20]=" "; unsigned int out[20]={0},decr[20]; int z; z=((p-1)*(q-1)); for(;;) { if(gcd(e,z)==1) break; e--; } for(;;) { if((e*d)%z==1) break; d++; } printf("enter the input string:\n"); gets(in); DSCE, Bangalore
43
Dept. of CSE NETWORK PROGRAMMING LAB MANUAL printf("\nThe entered string is: %s",in); printf("\n"); for(i=0;i<strlen(in);i++) { out[i]=mod_exp(in[i],e,n); printf("%c=%3d\n",in[i],out[i]); } printf("\nDecrypted string is: "); for(i=0;i<strlen(in);i++) { decr[i]=mod_exp(out[i],d,n); printf("%c",(char)decr[i]); } printf("\n"); return 0; } OUTPUT:Enter the input String: beta The entered String is: beta b = 131 e=2 t = 116 a = 218 Decrypted String is: beta
PROGRAM 7 Write a Program in C/ C++ for hamming code generation for error detection/correction Hamming Code is used to detect and correct single bit error. The key to Hamming Code is the use of extra parity bits. Hamming code consists of k information bits and n-k check bits ,where n is the total number of bits in the codeword. Parity bits are placed in positions having power of 2. To implement (7,4) HAMMING CODE: The Hamming Code for 4-bits of data uses 3 redundant bits. Hamming Code for 4 data bits d4 is DSCE, Bangalore 44 d3 d2 d1
d1 b3
r2 b2
where r1 r2 and r3 are redundant bits. PROCEDURE FOR DETERMINING REDUNDANT BITS: The ability of detecting and correcting errors of Hamming Code comes with the cost of redundant bits. These 3-bits are used to take care of all the 8 different possible states of transmitted 7-bits.
These equations are further solved to calculate r-bits: r1 = d1 + d2 + d4 r2 = d1 + d3 + d4 r3 = d2 + d3 + d4 PROCEDURE FOR ERROR DETECTION AND CORRECTION:
These values indicate one of the eight possible states of received code: --------------------------------------------------------p3 p2 p1 state Action for correction --------------------------------------------------------0 0 0 No error -0 0 1 Error in b1 bit Flip b1 0 1 0 Error in b2 bit Flip b2 0 1 1 Error in b3 bit Flip b3 1 0 0 Error in b4 bit Flip b4 1 0 1 Error in b5 bit Flip b5 1 1 0 Error in b6 bit Flip b6 1 1 1 Error in b7 bit Flip b7 --------------------------------------------------------45
DSCE, Bangalore
Dept. of CSE
And d4-d1 bits after this operation are the actual transferred data bits. Steps to execute the program At Sender: Code Formation: 1. Get 4-bit(d4-d1) input 2. Determine r-bits(r3-r1) using above equations 3. Form the 7-bit Code by placing r-bits and d-bits in appropriate positions. 4. Send the Code to Receiver At receiver: Error Detection and Correction: 1. Determine position bits(p3-p1) using above equations 2. Use the Table to find the position of error(if present) and to take corrective action. Program in C/ C++ for hamming code generation for error detection/correction //For Encoding #include<stdio.h> #include<math.h> main() { int i,j,k,count,error_pos=0,flag=0; char dw[20],cw[20],data[20]; printf("enter the data as binary bit stream 7 bits\n"); scanf("%s",data); for(i=1,j=0,k=0;i<12;i++) { if(i==(int)pow(2,j)) { dw[i]='?'; j++; } else { dw[i]=data[k]; k++; } } for(i=0;i<4;i++) { count=0; for(j=(int)pow(2,i);j<12;j+=(int)pow(2,i)) { for(k=0;k<(int)pow(2,i);k++) { if(dw[j]=='1') count++; j++; } } DSCE, Bangalore 46
Dept. of CSE
if(count%2 == 0) dw[(int)pow(2,i)]='0'; else dw[(int)pow(2,i)]='1'; } printf("\n CODE WORD is \n\n"); for(i=1;i<8;i++) printf("%c",dw[i]); printf("\n\nenter the received hamming code\n\n"); scanf("%s",cw); for(i=12;i>0;i--) cw[i]=cw[i-1]; for(i=0;i<4;i++) { count=0; for(j=(int)pow(2,i);j<12;j+=(int)pow(2,i)) { for(k=0;k<(int)pow(2,i);k++) { if(cw[j]=='1') count++; j++; } } if(count%2 != 0) error_pos=error_pos+(int)pow(2,i); } if(error_pos ==0) printf("\n\n There is no ERROR in received Code Word\n"); else{ if(cw[error_pos]==dw[error_pos]) { printf("\n\nThere are TWO or MORE Errors in received Code Word\n\n"); printf("SORRY........! Hamming code cannot correct TWO or MORE Errors\n"); flag=1; } else printf("\nThere is an Error in bit position %d of received Code Word \n\n",error_pos); if(flag==0) { if(cw[error_pos]=='1') cw[error_pos]='0'; else cw[error_pos]='1'; DSCE, Bangalore 47
Dept. of CSE
printf("\n\nCORRECTED CODE WORD is \n\n"); for(i=1;i<8;i++) printf("%c",cw[i]); } } printf("\n\n"); } OUTPUT:[root@localhost ~]# cc hm.c -lm [root@localhost ~]# ./a.out enter the data as binary bit stream 7 bits 1010 CODE WORD is 1011010 enter the received hamming code 1001010 There is an Error in bit position 3 of received Code Word CORRECTED CODE WORD is 1011010 [root@localhost ~]# ./a.out enter the data as binary bit stream 7 bits 1010 CODE WORD is 1011010 enter the received hamming code 1101010 There are TWO or MORE Errors in received Code Word SORRY........! Hamming code cannot correct TWO or MORE Errors PROGRAM 8 Write a Program in C/ C++ for congestion control using Leaky Bucket algorithm Leaky bucket is a traffic-shaping algorithm implemented by the sender in a network. The algorithm provides for a steady data transmission rate irrespective of the variation in data generation rate. The program for implementation leaky bucket algorithm can be viewed in two parts 1. Generation of data in variable bursts. 2. Data transmission at a constant rate. Leaky bucket can be implemented using a circular queue to hold data before it can be transmitted. The size of the circular queue is the size of the bucket size. The data generated from the process is inserted into the queue. When the queue is full, the generated data is discarded. Data get removed from the queue in FIFO fashion. DSCE, Bangalore 48
Dept. of CSE
By using interval timers, generate data in random bursts and store them to bucket. Using timers data from the bucket can be transmitted at a constant rate periodically. Setitimer API is use to set interval timers to the process to carry out the above functions. The API is defined in sys/time.h header file. Setitimer API prototype: int setitimer (int which, const struct itimerval *val, struct itimerval *old); Setitimer allows up to three timers to be set for a process, and offers a resolution time in microseconds. Expiry of the timer generates signal determined by the which argument in the API that can be either TIMER_REAL (SIGALRM) or TIMER_VIRTUAL (SIGVTALRM) or TIMER_PROF (SIGPROF). We can use the API to set two timers, for generating data and for transmitting data. When the timers go off respective actions associated with the signal handler are called to perform the operations. For generating random burst of data we use the random () function when the timer associated with data generation goes off. Socket programming or FIFO files can be use to transmit data to the receiver. Steps to execute the program: Main function 1. Establish connection from Sender to Receiver using socket programming or FIFO files. 2. Associate Send_data procedure to handle SIGALRM signal 3. Associate Generate_data procedure to handle SIGVTARLM signal. 4. Set the timer values for ITIMER_REAL timer and ITIMER_VIRTUAL timer in microseconds. 5. Set up the two timers using setitimer API. 6. WHILE TRUE DO a. wait for timers to go off periodically Generate_data function: 4. Generate a packet. 5. IF bucket (queue) is full DO Discard the packet generated. ELSE Insert the generated data into the bucket (queue). Send_data function: DSCE, Bangalore 49
a. Remove data form bucket (queue). b. Send the removed data to the receiver. ELSE Display Bucket empty. Program in C/ C++ for congestion control using Leaky Bucket algorithm #include<stdlib.h> #include<stdio.h> #include<math.h> int t_rand(int a) { int rn; rn = random()%10; rn=rn%a; if(rn == 0) rn = 1; return rn; } int main() { int packets[5],i,j,clk,b_size,o_rate,p_sz_rm=0,p_sz,p_time; system("clear"); for(i=0;i<5;i++) packets[i] = t_rand(6)*10; printf("\n Enter the output rate: "); scanf("%d",&o_rate); printf("\n Enter the Bucket size: "); scanf("%d",&b_size); for(i=0;i<5;++i) { if((packets[i]+p_sz_rm)>b_size) { if(packets[i] > b_size) printf("\n Incoming packet size (%d) is Greater than Bucket capacity Rejected",packets[i]); else printf("\n Bucket capacity exceeded Rejected"); } else { for(j=0;;++j) { DSCE, Bangalore 50
Dept. of CSE
p_sz = packets[i]; p_sz_rm += p_sz; printf("\n Incoming Packetsize: %d",p_sz); printf("\n Transmission Left: %d",p_sz_rm); p_time = t_rand(4)*10; printf("\n Next packet will come at: %d sec",p_time); for(clk=0;clk<=p_time;clk+=10) { printf("\n Time Left: %d sec",p_time-clk); sleep(1); if(p_sz_rm) { printf("--Transmitted"); if(p_sz_rm <= o_rate) p_sz_rm; else p_sz_rm -= o_rate; printf("--Bytes Remaining: %d",p_sz_rm); } else printf("--No packet to transmit \n"); } break; } } } printf("\n\n"); return 0; } OUTPUT:Enter the output rate:5 Enter the Bucket size:20 Incoming packet sz: 10 Transmissiom left:10 Next packet will come at:30 Time left:30- Transmitted !!-Bytes remaining:5 Time left:20- Transmitted !!-Bytes remaining:0 Time left:10-No packets to transmit !! Time left:0-No packets to transmit !! Incoming packet sz: 10 Transmissiom left:10 Next packet will come at:10 Time left:10- Transmitted !!-Bytes remaining:5 Time left:0- Transmitted !!-Bytes remaining:0 Incoming packet sz: 20 Transmissiom left:20 DSCE, Bangalore 51
Dept. of CSE NETWORK PROGRAMMING LAB MANUAL Next packet will come at:10 Time left:10- Transmitted !!-Bytes remaining:15 Time left:0- Transmitted !!-Bytes remaining:10 Incoming packet sz: 10 Transmissiom left:20 Next packet will come at:10 Time left:10- Transmitted !!-Bytes remaining:15 Time left:0- Transmitted !!-Bytes remaining:10 Incoming packet sz: 10 Transmissiom left:20 Next packet will come at:20 Time left:20- Transmitted !!-Bytes remaining:15 Time left:10- Transmitted !!-Bytes remaining:10 Time left:0- Transmitted !!-Bytes remaining:5
DSCE, Bangalore
52
DSCE
DSCE, Bangalore
53
DSCE
45. 46. 47. 48. 49. 50. 51. 52. 53. 54. 55. 56. 57. 58. 59. 60. 61. 62. 63. 64. 65. 66. 67. 68. 69. 70. 71. 72. 73. 74. 75. 76. 77. 78. 79.
What are Routing algorithms? How do you classify routing algorithms? Give examples for each. What are drawbacks in distance vector algorithm? How routers update distances to each of its neighbor? How do you overcome count to infinity problem? What is cryptography? How do you classify cryptographic algorithms? What is public key? What is private key? What are key, ciphertext and plaintext? What is simulation? What are advantages of simulation? Differentiate between Simulation and Emulation. What is meant by router? What is meant by bridge? What is meant by switch? What is meant by hub? Differentiate between route, bridge, switch and hub. What is ping and telnet? What is FTP? What is BER? What is meant by congestion window? What is BSS? What is incoming throughput and outgoing throughput? What is collision? How do you generate multiple traffics across different sender-receiver pairs? How do you setup Ethernet LAN? What is meant by mobile host? What is meant by NCTUns? What are dispatcher, coordinator and nctunsclient? Name few other Network simulators Differentiate between logical and physical address. Which address gets affected if a system moves from one place to another place? What is ICMP? What are uses of ICMP? Name few. Which layer implements security for data?
DSCE, Bangalore
54