Top Banner
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Laboratory Name : Network Laboratory Subject Code : CS1305 Ex.No NAME OF THE PROGRAM 1. Simulation of Address Resolution Protocol (ARP) / Reverse Address Resolution Protocol (RARP). 2. Implementation of bit stuffing and CRC Computation. 3. File Transfer Protocol Using RS232 Interface. 4. Simulation of Sliding-Window protocol. 5. Implementation of Open Shortest Path Finding (OSPF)/ Border Gateway Protocol (BGP) routing protocols 6. Client Server Chat using TCP / IP. 7. TCP Connection Establishment. 8. UDP Connection Establishment. 9. Domain Name System Implementation. 10. Download a file from a HTTP Server. 11. Study of Network Simulator (NS2)
58

Network Lab Man Aual

Apr 11, 2015

Download

Documents

rajapoornima

Network Lab Manual
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Network Lab Man Aual

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Laboratory Name : Network Laboratory Subject Code : CS1305

Ex.No NAME OF THE PROGRAM

1.Simulation of Address Resolution Protocol (ARP) / Reverse Address Resolution Protocol (RARP).

2. Implementation of bit stuffing and CRC Computation.

3. File Transfer Protocol Using RS232 Interface.

4. Simulation of Sliding-Window protocol.

5.Implementation of Open Shortest Path Finding (OSPF)/ Border Gateway Protocol (BGP) routing protocols

6. Client Server Chat using TCP / IP.

7. TCP Connection Establishment.

8. UDP Connection Establishment.

9. Domain Name System Implementation.

10. Download a file from a HTTP Server.

11. Study of Network Simulator (NS2)

Page 2: Network Lab Man Aual

1. IMPLEMENTATION OF ARP/RARP

AimTo write a C program to simulate the ARP/RARP protocol.

Theory

The Address Resolution Protocol (ARP) is a computer networking protocol for determining a network host's link layer or hardware address when only its Internet Layer (IP) or Network Layer address is known. This function is critical in local area networking as well as for routing internetworking traffic across gateways (routers) based on IP addresses when the next-hop router must be determined. ARP is most frequently used to translate IP addresses to Ethernet MAC addresses.

The Inverse Address Resolution Protocol (Inverse ARP or InARP), is a protocol used for obtaining Network Layer addresses (e.g., IP addresses) of other nodes from Data Link Layer (Layer 2) addresses (MAC addresses).

Algorithm

1. Include necessary header files.2. Use switch case to choose the server and client mode.3. In server mode get the logical and physical address from the user and write it

into the file.4. In client mode use switch case to choose IP to MAC or MAC to IP.5. In IP to MAC get IP address from user and compare with the IP address in

file.if matches then print the corresponding MAC address.

6. In MAC to IP get MAC address from user and compare with the MAC address in file,if matches then print the corresponding IP address.

7. If the format is wrong print wrong format.8. End of the program.

Program

#include<stdio.h>main(){ FILE *f; char log[20],log2[20],log1[20],mac[20],mac1[20],mac2[20]; int ch,ch1,i=0; printf("\n1. Server mode"); printf("\n2. Client mode"); printf("\nEnter your choice : "); scanf("%d",&ch1); switch(ch1) { case 1: printf("\nWelcome to server mode"); printf("\nEnter the logical IP and physical address\n"); scanf("%s %s",log2,mac2); f=fopen("new.txt","w"); fprintf(f,"%s %s",log2,mac2);

Page 3: Network Lab Man Aual

fprintf(f,"\n"); fclose(f); exit(0); case 2: printf("\nWelcome to client mode"); printf("\n1. Logical IP to MAC \n2. MAC to logical IP\n"); printf("Enter your choice : "); scanf("%d",&ch); f=fopen("new.txt","r"); switch(ch) { case 1: printf("\nEnter the logical IP : "); scanf("%s",log); while(!feof(f)) { fscanf(f,"%s %s",log1,mac1); if(strcmp(log,log1)==0) { printf("\nThe physical address : %s",mac1); i++; } else if(i==0) { printf("\nThe format is wrong"); exit(0); } } exit(0); case 2: printf("\nEnter the physical address : "); scanf("%s",mac); while(!feof(f)) { fscanf(f,"%s %s",log1,mac1); if(strcmp(mac,mac1)==0) { printf("\nThe logical IP address : %s",log1); i++; } else if(i==0) { printf("\nThe format is wrong\n"); exit(0); } } exit(0); } fclose(f); }}

Page 4: Network Lab Man Aual

Output

$ cc arp2.c$./a.out

1. Server mode2. Client modeEnter your choice : 1

Welcome to server modeEnter the logical IP and physical address192.168.1.1 45.21.BD.F2.23.FF$ ./a.out

1. Server mode2. Client modeEnter your choice : 2

Welcome to client mode1. Logical IP to MAC2. MAC to logical IPEnter your choice : 1

Enter the logical IP : 192.168.1.1

The physical address : 45.21.BD.F2.23.FF$ ./a.out

1. Server mode2. Client modeEnter your choice : 2

Welcome to client mode1. Logical IP to MAC2. MAC to logical IPEnter your choice : 2

Enter the physical address : 45.21.BD.F2.23.FF

The logical IP address : 192.168.1.1

Result

Thus the C program to simulate ARP/RARP protocol is written, entered, executed and results are verified.

Page 5: Network Lab Man Aual

2 (a) IMPLEMENTATION OF BIT STUFFING

Aim To write a C program to implement the bit stuffing.

TheoryIn data transmission and telecommunication, bit stuffing is the insertion of

no information bits into data. Stuffed bits should not be confused with overhead bits.Bit stuffing is used for various purposes, such as for bringing bit streams that do

not necessarily have the same or rationally related bit rates up to a common rate, or to fill buffers or frames. The location of the stuffing bits is communicated to the receiving end of the data link, where these extra bits are removed to return the bit streams to their original bit rates or form. Bit stuffing may be used to synchronize several channels before multiplexing or to rate-match two single channels to each other.

Algorithm

1. Start the program.2. Get the data bits from the user.3. If the data bit is ‘1’ then increment the counter.4. If the counter value reaches 5 insert ‘0’ in the data bit.5. Repeat the step 4,5 until a ‘$’ symbol is encountered.6. Print the stuffed data.7. Repeat the step 4 to dyestuff the data.8. If counter value reaches 5 then remove(dyestuff) ‘0’ from the data bits.9. Print the destuffed data.10. End of the program.

Program

#include<stdio.h>#include<string.h>main(){ char ch,ip[50],sip[50],dsip[50]; int i=0,j=0,k=0,t=0,l,m=0; printf("\nEnter the input bit sequence : "); while((ch=getchar())!='$') { ip[j]=ch; sip[i]=ch; if(ch=='1') { t++; if(t==5) { t=0; sip[i+1]='0'; i=i+1; } } if(ch=='0') t=0;

Page 6: Network Lab Man Aual

i=i+1;j=j+1; } sip[i+1]='\0'; printf("\nStuffed bit sequence : %s",sip); t=0;sip[i]='$'; while(sip[k]!='$') { dsip[m++]=sip[k]; if(sip[k]=='1') t++; if(t==5) { k++; t=0; } if(sip[k]=='0') t=0; k++; } dsip[m++]='\0'; printf("\nDestuffed bit sequence : %s\n",dsip);

}

Output

$ cc stuff.c$ ./a.outEnter the input bit sequence : 111111111111111111111111$Stuffed bit sequence : 1111101111101111101111101111Destuffed bit sequence : 111111111111111111111111

ResultThus the C program to implement bit stuffing is written, entered, executed and

results are verified.

Page 7: Network Lab Man Aual

2 (b) IMPLEMENTATION OF CRC GENERATION AND CHECKING

Aim To write a C program to implement Cyclic Redundancy Check code.

Theory

Cyclic Redundancy Check(CRC) is used for detecting errors in the data received from the sender. CRC is based on binary division.In CRC, instead of adding bits to achieve the desired parity, a sequence of redundant bits, called the CRC or the CRC remainder, is appended to the end of the data unit so that the resulting data unit becomes exactly divisible by a second, predetermined binary number. At its destination, the incoming data unit is assumed to be intact and is therefore accepted. A remainder indicates that the data unit has been damaged in transit and therefore must be rejected.

Algorithm

1. Start the program.2. Get the generator bits and data bits from the user.3. Find the length of the generator and data bits.4. Append [length of generator -1] ‘0’s in data bits.5. Call the function to perform mod2division with parameters data and generator

bits return checksum as a result.6. Join the data bits and checksum.7. Print the transmitted bits.8. Get the received bits from the user.9. Repeat step 5 and 6.10. Print the received bits and remainder (checksum).11. If the checksum is 000 then print received bit is accepted otherwise print

rejected.12. End of the program.

Program

#include<stdio.h>#include<string.h>#define MAX 10void mod2div(char divd[],char divs[]){ int i; if((strlen(divd))<(strlen(divs))) return; if(divd[0]=='1') { for(i=0;i<strlen(divs);i++) { if(divd[i]==divs[i]) divd[i]='0'; else divd[i]='1'; } }

Page 8: Network Lab Man Aual

for(i=0;i<strlen(divd)-1;i++) divd[i]=divd[i+1]; divd[i]='\0'; mod2div(divd,divs);}

int main(){ char gen[10],data[10],trans[2*MAX],chks[2*MAX],rec[2*MAX]; int r,m,i; printf("\nEnter the generator bits : "); scanf("%s",gen); printf("\nEnter the data bits to be transmitted : "); scanf("%s",data); printf("\nGenerator : %s",gen); printf("\nData : %s",data); r=strlen(gen); m=strlen(data); strcpy(chks,data); strcpy(trans,data); for(i=m;i<r+m-1;i++) chks[i]='0'; chks[i]='\0'; mod2div(chks,gen); printf("\nCRC : %s",chks); strcat(trans,chks); printf("\nTransmitted bits : %s",trans); printf("\nEnter the Received bits : "); scanf("%s",rec); strcpy(chks,rec); printf("\nReceived bits : %s",rec); mod2div(chks,gen); printf("\nRemainder : %s",chks); printf("\nHence %s is received",rec); if(atoi(chks)==0) { printf("\nAccepted"); rec[strlen(rec)-(r-1)]='\0'; printf("\nData bits : %s",rec); } else { printf("\nRejected"); } getchar(); return 0;}

Output

$ cc crc1.c$ ./a.out

Page 9: Network Lab Man Aual

Enter the generator bits : 1101

Enter the data bits to be transmitted : 100100000

Generator : 1101Data : 100100000CRC : 101Transmitted bits : 100100000101Enter the Received bits : 100100000101

Received bits : 100100000101Remainder : 000Hence 100100000101 is receivedAcceptedData bits : 100100000

Enter the Received bits : 100100010101

Received bits : 100100010101Remainder : 111Hence 100100010101 is receivedRejected

Result

Thus the C program to implement Cyclic Redundancy Check is written, entered, executed and results are verified.

Page 10: Network Lab Man Aual

3. FILE TRANSFER USING RS-232 INTERFACINGAim

To write a C program to implement a File Transfer Protocol Using RS232 Interface.

Theory

RS-232 (Recommended Standard 232) is a standard for serial binary data signals connecting between a DTE (Data Terminal Equipment) and a DCE (Data Circuit-terminating Equipment). It is commonly used in computer serial ports. The DCE and DTE are linked via a cable whose length does not exceed 50 feet. The DTE has 35 pins male connector and DCE has 25 pins Female connector.

RS232 Signal LEVEL RS232 standard follows –ve logic, Logic1 is represented by negative voltage.,

logic0 is represented by +ve voltage. Level 1 varies from -3 to -15v and level 0 varies from 3 to 15v

RS232 SIGNALS

SL NO PIN NUMBER SIGNAL SIGNAL NAME1 1 --- Frame ground2 2 TXD Transmit data3 3 RXD Receive data4 4 RTS Request to send5 5 CTS Clear to send6 6 DSR Data Set Ready7 7 SG Signal Ground8 8 RLSD or CD Received line signal detect or carrier detect9 20 DTR Data Terminal Ready10 22 RI Ring Indicator

Algorithm

Server

1. Start the program2. Include the necessary files and declare the necessary variables3. Create the client socket and initialize the file pointer.4. Check for errors in socket creation.5. Initialize the port, family, and address.6. Check for errors in connection establishment between client and server.7. Enter the source file name and destination file name.8. Send the file names to the server.9. Receive the contents of source file in the destination file.10. Close the file pointer and client socket.11. Stop the program

Client

Page 11: Network Lab Man Aual

1. Start the program2. Include the necessary header files and declare the necessary variables.3. Initialize the server socket and port.4. Declare the file pointer.5. Check for errors in socket creation and binding.6. Initialize the port, family, and address.7. Listen and accept client’s request.8. Receive the file names sent by the client.9. Copy the contents to destination and send the requested file to client.10. Close the file pointer and server socket.11. Stop the program

Program

#include<stdio.h>#include<dos.h>#include<stdlib.h>#include<conio.h>#define COM1 0x3f8#define RXER 1#define TXER 32#define LC 3#define LS 5void receivefile(){ FILE *fp; char status,ch=NULL; char *fname; printf("\nEnter the file name to be received : "); scanf("%s",fname); fp=fopen(fname,"w+"); do { status=inportb(COM1+LS); if((status&RXER)==RXER) { ch=inportb(COM1); printf("%c",ch); fputc(ch,fp); if(ch=='#') { printf("\nFile received successfully"); fclose(fp); return; } } }while(1);}void transferfile(){ FILE *fp;

Page 12: Network Lab Man Aual

char *fname,ch; printf("\nEnter the file name to be transferred : "); scanf("%s",fname); fp=fopen(fname,"r"); do { if((inportb(COM1+LS)&TXER)==TXER) { ch=fgetc(fp); printf("%c",ch); outportb(COM1,ch); if(ch=='#') break; } }while(1); fclose(fp); printf("\nFile sent successfully");}void initialize(){ _AH=0x00; _DX=0x00; _AL=0x07; geninterrupt(0x1);}void main(){ int ch; clrscr(); initialize(); printf("Select : Send / Receive (1/2) : "); scanf("%d",&ch); if(ch==1) transferfile(); if(ch==2) receivefile(); getch();}

Output

Sender:Select: Send/Receive (1/2):1Enter the file name to be sent : vijayVijayKarthiKathir #

File sent Successfully

Receiver:Select: Send/Receive (1/2):2

Page 13: Network Lab Man Aual

Enter the file name to be received : vijayVijayKarthiKathir #

File Received Successfully

Result

Thus the C program to implement File Transfer Protocol using RS-232 is written, entered, executed and the results are verified.

Page 14: Network Lab Man Aual

4. A. SLIDING WINDOW PROTOCOL - GO BACK –N

AimTo write a C program to implement sliding widow protocol using Go Back N

ARQ.

Theory

1. Stop and Wait is inefficient when propagation delay is larger than the packet transmission time

2. Can only send one packet per round-trip time 3. Go Back N allows the transmission of new packets before earlier ones are

acknowledged 4. Go back N uses a window mechanism where the sender can send packets that are

within a “window” (range) of packets 5. The window advances as acknowledgements for earlier packets are received.

Features of Go Back N

1. Window size = N 2. Sender cannot send packet i+N until it has received the ACK for packet i 3. Receiver operates just like in Stop and Wait 4. Receive packets in order 5. Receiver cannot accept packet out of sequence 6. Send RN = i + 1 => ACK for all packets up to and including i.

Use of piggybacking

1 When traffic is bi-directional RN’s are piggybacked on packets going in the other direction Each packet contains a SN field indicating that packet’s sequence number and a RN field acknowledging packets in other directions.

Algorithm

1. Include the necessary header files.2. A structure p1 and d1 is constructed to initialize frames and acknowledgement.3. Inside main( ) function get the number of frames and data .4. Set -1 for the frames without error. Else get the error frame as k.5. If any frame is lost or damaged, or the ACK acknowledging them is lost or damaged, then that frame and all following frames in the window (even if they were received without error) is re-sent before time out.6. If the frame is received after time out, it is discarded.7. Print the correctly received frame and the corresponding acknowledgement randomly.8. Execute the program.

Program#include<stdio.h>#include<conio.h>#include<time.h>#include<string.h>

Page 15: Network Lab Man Aual

#include<dos.h>struct pl{char f[20][20];int ack[20];}p;struct d1{char f[20][20];int ack[20];}d;int i,k,j,r,m,n;float t;clock_t a,b;void main(){clrscr();r=t=0;i=1;printf("Enter how many frames:");scanf("%d",&n);printf("\nEnter the data:");for(i=0;i<n;i++)scanf("%d",&p.f[i]);printf("\n Enter which frame received with error");printf("\n Enter -1 if no frame received with error:");scanf("%d",&k);m=k;if(k==-1)printf("All frames received correctly\n");elseif(k!=(-1)&&k<=n){for(i=1;i<k;i++){loop:strcpy(d.f[i],p.f[i]);printf("\nframe %d is received correctly",i);d.ack[i]=1;p.ack[i]=d.ack[i];printf("\nACK is sent for frame %d:",i);getch();}if(r!=1){a=clock();printf("\nframe %d is received with error",k);if(i!=1){printf("\nACK is sent for frame %d",i-1);}else

Page 16: Network Lab Man Aual

{printf("\n To ack");if(r==0)for(j=k+1;j<=n;j++){printf("\nframe %d is discarded",j);if(i!=1){printf("\n ack is sent for ack %d",i-1);}elseprintf("\n No ack");b=clock();t=(b-a)/CLK_TCK;delay(50);printf("\n%d",t);if(t>.001){printf("Timeout occurs so retransmetting errored frame\n");k=n+1;r=1;goto loop;}}}if(r!=1)if((n-m)<=2){r=1;printf("retransmitting without timeout\n");k=n+1;goto loop;}printf("\n All the frames received received correctly");getch();}}}

OutputEnter how many frames:5

Enter the data:12345

Enter which frame received with errorEnter -1 if no frame received with error:-1All frames received correctly

Page 17: Network Lab Man Aual

Result

Thus a C program to implement sliding window protocol using Go Back N ARQ is written, entered, executed and output is verified.

Page 18: Network Lab Man Aual

4. B. SLIDING WINDOW PROTOCOL - SELECTIVE REPEAT ARQ

Aim

To write a C program to implement sliding window protocol using selective repeat ARQ.

Theory1 Selective Repeat attempts to retransmit only those packets that are actually lost

(due to errors) 2 – Receiver must be able to accept packets out of order 3 – Since receiver must release packets to higher layer in order, the receiver must be

able to buffer some packets 4 • Retransmission requests 5 – Implicit

The receiver acknowledges every good packet, packets that are not

ACKed before a time-out are assumed lost or in error

Notice that this approach must be used to be sure that every

packet is eventually received

1 – Explicit An explicit NAK (selective reject) can request retransmission of just one packet This approach can expedite the retransmission but is not strictly needed 2 – One or both approaches are used in practice 3SRP rules

1 Window size W 2 • Packets are numbered Mod M where M >= 2W 3 • Sender can transmit new packets as long as their number is with W of all un-ACKed packets 4 • Sender retransmit un-ACKed packets after a timeout or upon a NAK if NAK is employed 5 • Receiver ACKs all correct packets 4 • Receiver stores correct packets until they can be delivered in order to the higher layer

Algorithm

1. Include the necessary header files.2. A structure p1 and d1 is constructed to initialize frames and acknowledgement.3. Get the number of frames and data.4. Get the frame as k which is received with error. If there is no errors in the frames that are received initialize -1 for k.5. Check for (k! =-1) then print the frame that is with error 6. Send a negative acknowledgement (NACK) for the frame with error and retransmit the frame before time out.6. Else print the correctly received frame and the corresponding acknowledgement randomly.7. Execute the program.

Page 19: Network Lab Man Aual

Program5#include<stdio.h>#include<conio.h>#include<stdlib.h>#include<time.h>#include<string.h>#include<dos.h>struct p1{char f[20][20];int ack[20];}p;struct d1{ char f[20][20]; int ack[20]; }d;int i,k,j,r,m,n,z;void main(){clrscr();i=1;printf("enter how many frames : ");scanf("%d",&n);printf("enter the data\n");for(i=1;i<=n;i++)scanf("%d",&p.f[i]);printf("\nenter which frame recd with error");printf("\nenter -1 if no frame recd with error");scanf("%d",&k);if(k!=1){for(i=1;i<=n;i++){if(i==k){printf("\nframe %d is recd with error\n",k);printf("\nnegative ack for frame %d\n",k);i++;m=k;goto loop;}printf("\nframe %d is read correctly\n",i);}}loop:{for(i=k;i<=n;i++){printf("\nframe %d is recd correctly",i);}

Page 20: Network Lab Man Aual

randomize();for(i=1;i<=n;i++)printf("\nack is sent for frame %d",rand());if(k!=-1)printf("\nack is sent for frame %d \n",k);getch();}}

Outputenter how many frames : 3enter the data1 2 3

enter which frame recd with errorenter -1 if no frame recd with error-1

frame 1 is read correctly

frame 2 is read correctly

frame 3 is read correctly

frame 1 is recd correctlyframe 2 is recd correctlyframe 3 is recd correctlyack is sent for frame 29659ack is sent for frame 147ack is sent for frame 19460

ResultThus a C program to implement sliding window protocol using selective repeat

ARQ is written, entered, executed and output is verified.

Page 21: Network Lab Man Aual

5. SHORTEST PATH CALCULATION IN OSPF

AimTo write a C program to find the shortest path between the nodes of a directed

graph using OSPF algorithm

Theory

OSPF stands for "Open Shortest Path First." OSPF is a method of finding the shortest path from one router to another in a local area network (LAN). As long as a network is IP-based, the OSPF algorithm will calculate the most efficient way for data to be transmitted.

If there are several routers on a network, OSPF builds a table (or topography) of the router connections. When data is sent from one location to another, the OSPF algorithm compares the available options and chooses the most efficient way for the data to be sent. This limits unnecessary delays in data transmission and prevents infinite loops.

OSPF uses the shortest path first (SPF) algorithm, also referred to as the Dijkstra algorithm, to determine the route to reach each destination. All routers in an area run this algorithm in parallel, storing the results in their individual topological databases. Routers with interfaces to multiple areas run multiple copies of the algorithm.

Algorithm

1. Mark each vertex as either known or unknown2. Tentative distance dv, from a source to a vertex, is kept3. Known vertices is determined by the distance that turns out to be the shortest path

length4. Select a vertex v, which has the smallest path dv among all the unknown vertices5. Declare the shortest path from source to vertex to known6. The remainder of a stage consists of updating the values of adjacent distance dw7. Set dw = dv + c(v,w) where c= cost of adjacent distance dw from vertex v, only if

dw is improved

Program

#include<stdio.h>#include<conio.h>struct edge{int vs,vd,wt;}a[20];void dj(int);int g[20][20];void main(){int n,i,j;printf("ENTER THE NO. OF VERTICES ");scanf("%d",&n);printf("ENTER THE DIRECTED ADJACENCY MATRIX\n");for(i=1;i<=n;i++)for(j=1;j<=n;j++)

Page 22: Network Lab Man Aual

scanf("%d",&g[i][j]);printf("THE MATRIX IS");for(i=1;i<=n;i++){printf("\n");for(j=1;j<=n;j++)printf("%d\t",g[i][j]);}dj(n);}void dj(int n){int i,p,j,k=0,st[20],l,sm,t=0,d,pred[20],dist[20],m[20],s;for(i=1;i<=n;i++)st[i]=0;for(i=1;i<=n;i++){for(j=1;j<=n;j++){if(g[i][j]>0){k++;a[k].vs=i;a[k].vd=j;a[k].wt=g[i][j];}}}printf("ENTER THE STARTING NODE ");scanf("%d",&s);st[s]=1;pred[s]=s;dist[s]=0;for(i=1;i<=n;i++){if(i!=s){pred[i]=i;dist[i]=9999;}}for(p=1;p<=k;p++){t=0;for(i=1;i<=k;i++){if((st[a[i].vs]==1)&&(st[a[i].vd]==0)){m[++t]=(a[i].wt+dist[a[i].vs]);}}sm=m[1];

Page 23: Network Lab Man Aual

for(l=2;l<=t;l++){if(m[l]<sm)sm=m[l];}for(i=1;i<=k;i++){if((st[a[i].vs]==1)&&(st[a[i].vd]==0)){if((a[i].wt+dist[a[i].vs])==sm){st[a[i].vd]=1;pred[a[i].vd]=a[i].vs;dist[a[i].vd]=a[i].wt+dist[a[i].vs];}}}

}printf(" PREDECESSOR ");for(i=1;i<=n;i++)printf(" %d ",pred[i]);printf("\nDISTANCE ");for(i=1;i<=n;i++)printf(" %d ",dist[i]);printf("\nENTER THE DESTINATION VERTEX ");scanf("%d",&d);printf("SHORTEST PATH IS ");printf("%d",d);while(d!=s){d=pred[d];printf("<-%d",d);}getch();}

OutputENTER THE NO. OF VERTICES 3ENTER THE DIRECTED ADJACENCY MATRIX312345678THE MATRIX IS

Page 24: Network Lab Man Aual

3 1 23 4 56 7 8 ENTER THE STARTING NODE 1 PREDECESSOR 1 1 1DISTANCE 0 1 2ENTER THE DESTINATION VERTEX 3SHORTEST PATH IS 3<-1

Result

Thus a C program to find the shortest path between the nodes of a directed graph using OSPF algorithm is written, entered, executed and output is verified.

Page 25: Network Lab Man Aual

6. CLIENT – SERVER CHAT USING TCP/IP

Aim:To write a C program for client – server chat using TCP

Theory

TCP

TCP stands for Transaction Control Protocol. This is one of the transport layer protocols. TCP offers a connection-oriented, reliable, byte stream service. This also provides a good flow control and congestion control. The term connection-oriented means any two applications using TCP must establish a connection with each other before they can exchange data. This can be done by using three-way handshaking.

Data is divided into small chunks and each chunk of data is called as Segments. The data sent using TCP follows a single route and it can be in out-of-order. The receiver will rearrange the data using the sequence numbers.

Flow control is established by using a finite amount of buffer space on both sides. With this the receiver allows the sender to send only the amount of data it can accept in the buffer. TCP also provides error control. A checksum is maintained in the header and data.

Services provided by TCP

• Connection- oriented: setup required between client, server• Reliable transport between sending and receiving process• Flow control: sender won’t overwhelm receiver• Congestion control: throttle sender when network overloaded

Services not provided by TCP

• Timing and minimum bandwidth.

Algorithm

Server

1. Start the program.2. Include all the necessary header files and declare necessary variables.3. Create a stream socket “sersock” using socket() and check if the socket is created

successfully or not.4. Initialize the server socket structure variable – ser_ip(family, port & address).5. Use bind() to assign the local socket address ser_ip to the socket identified by

sersock.6. Accept the request to connect from the client by using the accept() and store the

socket information in nsersock.7. Send and receive data to and from the client by using send () & recv()

respectively. Print the received data.8. Goto step 7 until client sends “exit”.9. Close all open sockets.10. Stop the program.

Page 26: Network Lab Man Aual

Client

1. Start the program.2. Include all the necessary header files and declare necessary variables.3. Create a stream socket “clisock” using socket() and check if the socket is created

successfully of not.4. Initialize the client socket structure variable – cli_ip(family, port & address).5. Send a request to connect with the server using connect().6. Send and receive data to and from server using send() & recv() respectively.7. Repeat step 6 until either of the users wants to quit by typing “exit”.8. Close all open sockets.9. Stop the program.

Program

Server.c

#include<stdio.h>#include<unistd.h>#include<sys/types.h>#include<netinet/in.h>#include<string.h>#include<sys/socket.h>#include<stdlib.h>main(){ int sersock,port=2010,i=0,nsersock; struct sockaddr_in cli_ip,ser_ip; char content[100]=""; if((sersock=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP))==-1) { printf("Error in creating socket"); exit(0); } bzero((char*)&ser_ip,sizeof(ser_ip)); ser_ip.sin_family=AF_INET; ser_ip.sin_port=htons(port); ser_ip.sin_addr.s_addr=htonl(INADDR_ANY); if(bind(sersock,(struct sockaddr*)&ser_ip,sizeof(ser_ip))==-1) { printf("Port problem"); exit(0); } i=sizeof(cli_ip); listen(sersock,1); nsersock=accept(sersock,(struct sockaddr*)&cli_ip, &i); if(nsersock==-1) { printf("\nError: Client accepting problem"); exit(0); }

Page 27: Network Lab Man Aual

i=0; while(1) { if(!fork()) { i=recv(nsersock,content,10,0); content[i++]='\0'; if(!strcmp(content,"exit")) { printf("\nOther user wants to exit"); exit(0); } printf("\n"); printf("%s",content); } else { while(1) { fflush(stdin); scanf("%c",&content[i]); if(content[i++]=='\n') break; } if(i!=29) i--; content[i]='\0'; send(nsersock,content,strlen(content),0); if(!strcmp(content,"exit")) { printf("\nWrite mode on exit, you can't write more"); exit(0); } } } close(sersock); close(nsersock); }

Client.c

#include<stdio.h>#include<sys/types.h>#include<netinet/in.h>#include<sys/socket.h>#include<unistd.h>#include<string.h>#include<stdlib.h>main(){ int clisock,port=2010,i=0;

Page 28: Network Lab Man Aual

struct sockaddr_in cli_ip; char content[100]=""; if((clisock=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP))==-1) { printf("\nError in creating socket"); exit(0); } bzero((char*)&cli_ip,sizeof(cli_ip)); cli_ip.sin_family=AF_INET; cli_ip.sin_port=htons(port); cli_ip.sin_addr.s_addr=htonl(INADDR_ANY); if(connect(clisock,(struct sockaddr*)&cli_ip,sizeof(cli_ip))<0) { printf("\nConnection problem"); exit(0); } while(i<100) { content[i++]='\0'; i++; } i=0; while(1) { if(!fork()) { i=recv(clisock,content,30,0); content[i]='\0'; if(!strcmp(content,"exit")) { printf("Other user wants to exit, you can't read"); exit(0); } printf("\n"); printf("%s",content); } else { while(1) { fflush(stdin); scanf("%c",&content[i]); if(content[i++]=='\n') break; } if(i!=29) i--; content[i]='\0'; i=0; printf("\nData transmission"); send(clisock,content,strlen(content),10); printf("\n");

Page 29: Network Lab Man Aual

if(!strcmp(content,"exit")) { printf("\nUser in exit mode"); exit(0); } } } close(clisock); }

Output

$ ./server.outHiHow are you?

Other user wants to quit

$ ./client.outHiHow are you?

Data Transmissionexit

User in exit mode

Result

Thus the C program for client-server chat using TCP is written, entered, executed and the results are verified.

Page 30: Network Lab Man Aual

7. TCP CONNECTION ESTABLISHMENT

AimTo write a C program to establish and check the TCP connection between client

and Server.

Theory

TCP

TCP stands for Transaction Control Protocol. This is one of the transport layer protocols. TCP offers a connection-oriented, reliable, byte stream service. This also provides a good flow control and congestion control. The term connection-oriented means any two applications using TCP must establish a connection with each other before they can exchange data. This can be done by using three-way handshaking.

Data is divided into small chunks and each chunk of data is called as Segments. The data sent using TCP follows a single route and it can be in out-of-order. The receiver will rearrange the data using the sequence numbers.

Flow control is established by using a finite amount of buffer space on both sides. With this the receiver allows the sender to send only the amount of data it can accept in the buffer. TCP also provides error control. A checksum is maintained in the header and data.

Services provided by TCP • Connection- oriented: setup required between client, server• Reliable transport between sending and receiving process• Flow control: sender won’t overwhelm receiver• Congestion control: throttle sender when network overloaded

Services not provided by TCP• Timing and minimum bandwidth.

Algorithm

Server

1. Start the program2. Include all the necessary header files and declare necessary variables.3. Create a stream socket “sersock” using socket() and check if the socket is created

successfully or not.4. Initialize the server socket structure variable – ser_ip(family, port & address).5. Use bind() to assign the local socket address ser_ip to the socket identified by

sersock.6. Accept the request to connect from the client by using the accept() and store the

socket information in nsersock.7. Receive data from client by using recv() and print it.8. Close all open sockets.9. Stop the program.

Page 31: Network Lab Man Aual

Client

1. Start the program.2. Include all the necessary header files and declare necessary variables.3. Create a stream socket “clisock” using socket() and check if the socket is created

successfully of not.4. Initialize the client socket structure variable – cli_ip(family, port & address).5. Send a request to connect with the server using connect().6. Send data to the server using send().7. Close all open sockets.8. Stop the program.

Program

Server.c

#include<stdio.h>#include<unistd.h>#include<sys/types.h>#include<netinet/in.h>#include<string.h>#include<sys/socket.h>#include<stdlib.h>main(){int sersock,port=2010,i=0,nsersock;struct sockaddr_in cli_ip,ser_ip;char content[100]="";if((sersock=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP))==-1){printf("error in creating socket");exit(0);}bzero((char *)&ser_ip,sizeof(ser_ip));ser_ip.sin_family=AF_INET;ser_ip.sin_port=htons(port);ser_ip.sin_addr.s_addr=htonl(INADDR_ANY);#include<stdio.h>#include<unistd.h>#include<sys/types.h>#include<netinet/in.h>#include<string.h>#include<sys/socket.h>int main(){int sersock,port=2010,i=0,nsersock;struct sockaddr_in cli_ip,ser_ip;char content[100]="";if((sersock=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP))==-1){printf("error in creating socket");exit(0);

Page 32: Network Lab Man Aual

}bzero((char *)&ser_ip,sizeof(ser_ip));ser_ip.sin_family=AF_INET;ser_ip.sin_port=htons(port);ser_ip.sin_addr.s_addr=htonl(INADDR_ANY);if(bind(sersock,(struct sockaddr*)&ser_ip,sizeof(ser_ip))==-1){printf("port problem");exit(0);}i=sizeof(cli_ip);listen(sersock,1);nsersock=accept(sersock,(struct sockaddr*)&cli_ip,&i);if(nsersock==-1){printf("error ::client accepting problem");exit(0);}i=0;i=recv(nsersock,content,30,0);content[i]='\0';printf("\n");printf("%s",content);close(sersock);close(nsersock);}

Client.c

#include<stdio.h>#include<unistd.h>#include<sys/types.h>#include<netinet/in.h>#include<string.h>#include<sys/socket.h>#include<stdlib.h>main(){int clisock,port=2010,i=0;struct sockaddr_in cli_ip;char content[100];if((clisock=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP))<0){printf("error in creating socket");exit(0);}bzero((char *)&cli_ip,sizeof(cli_ip));cli_ip.sin_family=AF_INET;cli_ip.sin_port=htons(port);cli_ip.sin_addr.s_addr=htonl(INADDR_ANY);if(connect(clisock,(struct sockaddr*)&cli_ip,sizeof(cli_ip))==-1)

Page 33: Network Lab Man Aual

{printf("connection problem");exit(0);}while(i<100){content[i]='0';i++;}i=0;while(i<30){scanf("%c",&content[i]);if(content[i++]=='\n')break;}if(i!=29)i--;content[i]='\0';i=0;printf("data transmission");send(clisock,content,strlen(content),0);printf("\n");close(clisock);}

Output

$ ./client.outClient Module:Hi…Data Transmission

$ ./server.outServer Module:Hi…

Result

Thus the C program to establish and check TCP connection between client and server is written, entered, executed and the results are verified.

Page 34: Network Lab Man Aual

8. UDP CONNECTION ESTABLISHMENT

AimTo write a C program to establish and check UDP connection between client and

server.

Theory

UDP stands for User Datagram Protocol. It is one of the transport layer protocol. UDP offers a simple, connection-less, unreliable service. This does not offer error or flow control. As it is a connection-less protocol, there is no need for connection establishment or connection termination phases. So, the overhead is reduced in UDP.

Data is divided into small chunks called as Datagrams. There will be no relationship between packets. Each datagram is treated as individual packets even if they are a part of a large message. UDP datagrams may arrive in out-of-order, hence the receiver computer should take the responsibility of rearranging the datagrams. UDP has an inbuilt support for multicasting. Hence it is used mainly for multicasting applications.

Services provided by UDP• Connection-less: no connection is required between client & server.• Unreliable transport between sending and receiving process

Services not provided by UDP• Reliability• Flow control• Congestion control• Timing or bandwidth guarantee.

Algorithm

Server

1. Start the program.2. Include all the necessary header files and declare necessary variables.3. Create a datagram socket “sersock” using socket() and check if the socket is

created successfully or not.4. Initialize the server socket structure variable – ser_ip(family, port & address).5. Use bind() to assign the local socket address ser_ip to the socket identified by

sersock.6. Receive data from client by using recvfrom() and print it.7. Close all open sockets.8. Stop the program.

Client

1. Start the program.2. Include all the necessary header files and declare necessary variables.3. Create a datagram socket “clisock” using socket() and check if the socket is

created successfully or not.

Page 35: Network Lab Man Aual

4. Initialize the client socket structure variable – cli_ip(family, port & address).5. Send data to the server using sendto().6. Close all open sockets.7. Stop the program.

Program

Server.c

#include<stdio.h>#include<unistd.h>#include<sys/types.h>#include<netinet/in.h>#include<string.h>#include<sys/socket.h>#include<stdlib.h>main(){ int sersock,port=5000,i=0; struct sockaddr_in ser_ip,cli_ip; char content[100]; if((sersock=socket(AF_INET,SOCK_DGRAM,0))==1) { printf("Error in creating the socket"); } bzero((char *)&ser_ip,sizeof(ser_ip)); ser_ip.sin_family=AF_INET; ser_ip.sin_port=htons(port); ser_ip.sin_addr.s_addr=htonl(INADDR_ANY); printf("\nBefore bind");if(bind(sersock,(struct sockaddr*)&ser_ip,sizeof(ser_ip))==-1){printf("\nPort Problem, change port number");exit(0);}printf("\nAfter bind");i=sizeof(ser_ip);printf("\nData received from the client:");recvfrom(sersock,content,30,0,(struct sockaddr*)&cli_ip,&i);i=strlen(content);while(j<=i){printf("%c",&content[i]);j++;}close(sersock);}

Client.c

#include<stdio.h>#include<unistd.h>

Page 36: Network Lab Man Aual

#include<sys/types.h>#include<netinet/in.h>#include<string.h>#include<sys/socket.h>#include<stdlib.h>main(){ int clisock,port=5000,i=0; struct sockaddr_in cli_ip; char content[100]; if((clisock=socket(AF_INET,SOCK_DGRAM,0))==1) { printf("Error in creating the socket"); } bzero((char *)&cli_ip,sizeof(cli_ip)); cli_ip.sin_family=AF_INET; cli_ip.sin_port=htons(port); cli_ip.sin_addr.s_addr=htonl(INADDR_ANY); while(i<30) { scanf("%c",&content[i]); if(content[i++]=='\n') break; } if(i!=30) i--; content[i]='\0';printf("Data transmitted to the server is %s",content); sendto(clisock,content,strlen(content),0,(struct sockaddr*)&cli_ip,sizeof(cli_ip)); printf("Data Transmission"); close(clisock);}

Output

$ ./udpclient.outNetworksData Transmitted to the server : Networks

$ ./udpserver.outBefore Socket creationAfter Socket creationBefore bindAfter bindData received from client : Networks

Result

Thus the C program to establish and check UDP connection between client and server is written, entered, executed and the results are verified.

Page 37: Network Lab Man Aual

9. DOMAIN NAME SYSTEM IMPLEMENTATION

AimTo write a C program to resolve a domain name using DNS Server.

Theory

Domain Name System(DNS) is an application layer protocol. The main goal of DNS is to assign a meaningful high-level names called as Domain Names to a large set of machines and handle the mapping of those names to a machine’s IP address. DNS is a distributed database which resides on multiple machines on the internet. These machines are used to convert domain names into addresses and vice versa.

This uses the services of UDP and runs on the well-known port 53. The domain names are collectively called as Domain Name Space. The domain name space is of two types

1. Flat Name space2. Hierarchical Name spaceThe process of mapping the domain names with their corresponding IP address is

called Resolution. The vice versa is called Reverse Resolution. There are two types of resolution techniques. They are,

1. Recursive Resolution2. Iterative Resolution

An example of domain name is www.google.com, www.klnce.edu.

Algorithm

Server

1. Start the program2. Include the necessary header files and declare the necessary variables.3. Create a stream socket “sersock” using socket() and check if the socket is created

successfully or not.4. Initialize the server socket structure variable – ser (family, port & address).5. Use bind() to assign the local socket address ser to the socket identified by sd.6. Accept the request to connect from the client by using the accept() and store the

socket information in nsd.7. Receive the domain name from the DNS Client by using recv().8. If an entry for the received domain name exists in the server, then send the

corresponding IP address to the client, else send “Cannot resolve” to the client9. Close all open sockets.10. Stop the program.

Client

1. Start the program.2. Include all the necessary header files and declare necessary variables.3. Create a stream socket “sock” using socket() and check if the socket is created

successfully of not.4. Initialize the client socket structure variable – cli (family, port & address).5. Send a request to connect with the server using connect().

Page 38: Network Lab Man Aual

6. Send the domain name to be resolved to the DNS Server using send().7. Receive the reply from the server and print it.8. Close all open sockets.9. Stop the program.

Program

DNSServer.c

#include<stdio.h>#include<string.h>#include<sys/types.h>#include<sys/socket.h>#include<netinet/in.h>#include<unistd.h>#include<stdlib.h>main(){ int sd,nsd,r=0,j=0,i,cmp=0,port=2102; struct sockaddr_in ser,cli; char content[30]; char ipaddr[30]; char domain[10][40]={"www.google.com","www.yahoo.com"}; char ip[20][40]={"205.209.50.70","235.210.59.60"}; if((sd=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP))==0) { printf("\nError in creating the socket"); return (0); } bzero((char*)&ser,sizeof(ser)); ser.sin_family=AF_INET; ser.sin_port=htons(port); ser.sin_addr.s_addr=htonl(INADDR_ANY); if(bind(sd,(struct sockaddr*)&ser,sizeof(ser))==-1) { printf("\n::Binding problem"); exit(0); } printf("\nBefore Bind"); i=sizeof(cli); listen(sd,1); printf("\nServer module"); printf("\n****************"); nsd=accept(sd,(struct sockaddr*)&cli,&i); if(nsd==-1) { printf("pblm in the accepting client"); } printf("\nRECEIVING"); r=recv(sd,content,30,0);

Page 39: Network Lab Man Aual

content[r]='\0'; j=0; for(j=0;j<10;j++) { //cmp=strcmp(domain[j],content); //printf("\nthe cmp value is:%d",cmp); if(strcmp(domain[j],content)==1) { printf("\nmatch"); strcpy(ipaddr,ip[j]); break; } } send(nsd,ipaddr,30,0); if(j<=9) { strcpy(ipaddr,"cannot resolve"); send(nsd,ipaddr,30,0); } close(sd); close(nsd);}

DNSClient.c

#include<stdio.h>#include<string.h>#include<sys/types.h>#include<sys/socket.h>#include<netinet/in.h>#include<unistd.h>int main(){ int sock,r=0,i=0,port=2102; struct sockaddr_in cli; char content[30],c; if((sock=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP))==-1) { printf("Error in creating the socket"); return 0; } bzero((char*)&cli,sizeof(cli)); cli.sin_family=AF_INET; cli.sin_port=htons(port); cli.sin_addr.s_addr=htonl(INADDR_ANY); if(connect(sock,(struct sockaddr*)&cli,sizeof(cli))==-1) { printf("cannot connect"); return 0; } printf("\nEnter the domain name : "); c=getchar();

Page 40: Network Lab Man Aual

while(c=='#') { content[i]=c; c=getchar(); i++; } content[i+1]='\0'; send(sock,content,30,0); r=recv(sock,content,30,0); content[r]='\0'; printf("%s",content); close(sock);}

Output

$ ./dsnc.outClient ModuleEnter the domain name : www.google.com205.209.50.70

$ ./dnss.outServer Module******************RECEIVINGThe cmp value is 1match

Result

Thus the C program to resolve a domain name using DNS Server is written, entered, executed and the results are verified.

Page 41: Network Lab Man Aual

10. DOWNLOAD A FILE FROM A HTTP SERVER

AimTo write a C program to download a file from a HTTP server and display its

contents.

Theory

HTTP stands for Hyper Text Transfer Protocol. This is an application layer protocol used to access data on the World Wide Web (WWW). The protocol transfers data in the form of plain text, hyper text, audio and video and so on. This uses the services of TCP to transfer data and it uses a well-known port 80. Current version of HTTP is HTTP 1.1.

A client sends a request to the server, which looks like a mail sent to the server. Then server sends the response which looks like a mail reply to the client. The request and response messages carry data in the form of a letter with a MIME-like format

The figure shows a HTTP transaction.

HTTP messages are of two types, namely, 1. Request & 2. Response. There are many methods used to perform operations using HTTP. Some of them are,1. GET2. PUT3. HEAD4. POST5. COPY6. DELETE7. etc

Algorithm

1. Start the program.2. Include the necessary header files and declare the necessary variables.3. Create a stream socket “sockfd” using socket() and check if the socket is created

successfully or not.4. Retrieve the host id of the http server by using gethostbyname().5. Initialize the socket structure variable – serv_addr (family, port & address).6. Send GET message to the http server by using send().7. Receive the file from http server and store its contents.8. Print the received file’s contents.9. Close all open sockets.10. Stop the program.

Page 42: Network Lab Man Aual

Program

#include<stdio.h>#include<sys/types.h>#include<sys/socket.h>#include<netinet/in.h>#include<netdb.h>#include<errno.h>

#include<stdlib.h>

#include<string.h>

char buffer[6096];char buf[6096];void error(char *msg){perror(msg);exit(0);}main(int argc,char *argv[]){int sockfd,portno,n;struct sockaddr_in serv_addr;struct hostent *server;char buffer[4096];portno=80;sockfd=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);if(sockfd<0)error("ERROR opening socket");server=gethostbyname("www.google.com");if(server==NULL){fprintf(stderr,"ERROR,no such host\n");exit(0);}bzero((char *)&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("ERRORCORRECTION");strcpy(buffer,"GET http://www.google.com \r\n\r\nUser-Agent: vijay\r\n\n");//Host:192.168.0.254");n=send(sockfd,buffer,strlen(buffer),0);if(n<0)error("Error writing to socket");bzero(buf,4096);while((n=recv(sockfd,buf,sizeof(buf),0))!=0){buf[6095]='\0';

Page 43: Network Lab Man Aual

printf("Received:%s",buf);}close(sockfd);}

Output

$ ./a.outReceived:HTTP/1.0 302 FoundLocation: http://www.google.co.in/Cache-Control: privateContent-Type: text/html; charset=UTF-8Set-Cookie: PREF=ID=6de4506bfc45c567:TM=1255516287:LM=1255516287:S=x4Kpx6GNDP1poQXy; expires=Fri, 14-Oct-2011 10:31:27 GMT; path=/; domain=.google.comSet-Cookie: NID=27=J3r4GdeIut3M4VgvMeGVRLCX8MKt10T1UU9lztVWPwS5OyvLvTTdzZx54OzGG1DV8OCxurf6nuG9cz9rVEcb79gSudbA7k50Sr63K2BBUQc4IpKcvUWxiJue0_A5IXgv; expires=Thu, 15-Apr-2010 10:31:27 GMT; path=/; domain=.google.com; HttpOnlyDate: Wed, 14 Oct 2009 10:31:27 GMTServer: gwsContent-Length: 221X-XSS-Protection: 0

<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8"><TITLE>302 Moved</TITLE></HEAD><BODY><H1>302 Moved</H1>The document has moved<A HREF="http://www.google.co.in/">here</A>.</BODY></HTML>

Result

Thus the C program to download a file from a HTTP server and display its contents is written, entered, executed and the results are verified.

Page 44: Network Lab Man Aual

11. Study of Network Simulator NS2

Aim

To study about NS2 simulator

NS2 Simulation

NS is an event driven network simulation developed at UC Berkeley that simulator variety of IP networks. It implements network protocols such that TCP and UDP at UC Berkeley that simulator variety of IP networks.  It implements network protocols such that TCP and UDP traffic source behavior as FTP, Telnet, Web, CBR and VBR router queue management mechanism such as Droptail, RED and CBQ, routing algorithms such as Dijikstra’s and more. NS also implements multicasting and same of the MAC layer protocols for LAN situations.

Simplified Users view of NS

In a simplified user’s view, NS is an Object Oriented Tcl (OTcl) script interpreter that has simulation event Scheduler and Network component object libraries, and n/w setup module libraries. To setup and run a simulation n/w, a user should write an OTcl script that initiates an event scheduler, sets up the n/w topology using the n/w objects and the plumbing functions in the library and tells traffic sources when to start and stop transmitting packets through the event scheduler. The term “plumbing” is used for an n/w setup, because setting up an n/w is plumbing possible data paths among network objects by setting the “neighbor” pointer of an object. But the plumbing OTcl module actually makes the job very easy.

Another major component of NS beside network objects is the event scheduler. An event in NS is a packet with scheduled time and the pointer to an object that handles the event. Network components communicate with one another passing packets, however this does not consume actual simulation time. All the n/w components that need to spend some simulation time handling a packet use the even scheduler by issuing an event for the packet and waiting for the event to be fixed to itself before doing further switch with 20ks. Another use of an event scheduler is timer ,for ex, TCP needs a timer to keep track of a packet transmission time out for retransmission. The only difference is that timer measures a time value associated with a packet and does not simulate a delay.

A simply N/W topology and Simulation Scenario

This n/w consists of 4 nodes (n0, n1, n2, n3) as shown. The duplex links b/w n0 , n2 and n1 ,n2 have 2 mbps of bandwidth and 10ms of delay. The duplex link b/w n2 and n3 has 1.7 mbps of bandwidth and 20ms of delay. Each node uses a Drop tail queue of which of the maximum size is 10. A connection is established to a tcp “sink” agent attached to n3. A tcp “sink” agent generates and sends ACK packets. A “Udp” generates that is attached to n, is connected to a “null” agent attached to n3. The “cbr” is set to start at 0.1 sec and stop at 4.5 sec and “ftp” is sent to start at 1.0 sec and stop at 4.0 sec.

Page 45: Network Lab Man Aual

                #create a simulator object                set ns [new simulator]

                #define different colors for data flows [FOR NAM]                $ns color 1 blue                $ns color 2 Red

                #open the NAM source file                set nf [open out.nam  w]                $ns namtrace-all $nf

                #define ‘Finish’ procedure.                Proc finish {                                global ns OF                                $ ns flush-trace                                close $ns   #(close the event scheduler object.)                                exec nam out nam &   #(execute NAM file using this command.)                                exit 0                }

                #create four nodes                set n0 [$ns  node]                set n1 [$ns  node]                set n3 [$ns  node]                set n4 [$ns  node]

#create links between the nodes             $ns duplex-link $n0 & $n2 2mb 10ms Droptail             $ns duplex-link $n1 & $n2 2mb 10ms Droptail             $ns duplex-link $n2 & $n3 2mb 10ms Droptail

#set queue – limit size of link (n2-n3) to 10             $ns queue–limit $n2 $n3 10                #Give node position (for NAM)             $ns duplex – link –op $n2 orient right-down             $ns duplex – link – op $n1 orient right-up             $ns duplex – link – op $n2 $n3 orient right

#Monitor the queue for link (n2-n3) (for NAM)            $ns duplex-link-op $n2 $n3 queue-pos 0.5

  #Setup a TCP connection.                set tcp [new Agent/TCP]                $tcp set class 2                $ns attach-agent $n0 $tcp                set sink [ new Agent/TCP sink]                $ ns attach-agent $n3 $sink                $ ns connect  $tcp $sink

Page 46: Network Lab Man Aual

# Setup a FTP over TCP connectionset ftp [new Application / FTP]$ftp attach-agent $tcp

#Setup a FTP connection for particular time period.$ns at <time> “$ftp start”    # (start the FTP traffic generation)$ns at <time> “$ftp stop”    # (stop the FTP traffic generation)

Result

Thus the NS2 simulator and its features are studied

Page 47: Network Lab Man Aual

Important Functions used and its uses

bind - bind a name to a socket

The bind() function shall assign a local socket address address to a socket identified by descriptor socket that has no local socket address assigned. Sockets created with the socket() function are initially unnamed; they are identified only by their address family.

accept - accept a new connection on a socket

The accept() function shall extract the first connection on the queue of pending connections, create a new socket with the same socket type protocol and address family as the specified socket, and allocate a new file descriptor for that socket.

listen - listen for socket connections and limit the queue of incoming connections

The listen() function shall mark a connection-mode socket, specified by the socket argument, as accepting connections.

socket - create an endpoint for communication

The socket() function shall create an unbound socket in a communications domain, and return a file descriptor that can be used in later function calls that operate on sockets.

send - send a message on a socket

The send() function shall initiate transmission of a message from the specified socket to its peer. The send() function shall send a message only when the socket is connected (including when the peer of a connectionless socket has been set via connect()).

connect - connect a socket

The connect() function shall attempt to make a connection on a socket.

recv - receive a message from a connected socket

The recv() function shall receive a message from a connection-mode or connectionless-mode socket. It is normally used with connected sockets because it does not permit the application to retrieve the source address of received data.

recvfrom - receive a message from a socket

The recvfrom() function receives a message from a connection-mode or connectionless-mode socket. It is normally used with connectionless-mode sockets because it permits the application to retrieve the source address of received data.

Page 48: Network Lab Man Aual

sendto - send a message on a socket

The sendto() function shall send a message through a connection-mode or connectionless-mode socket. If the socket is connectionless-mode, the message shall be sent to the address specified by dest_addr. If the socket is connection-mode, dest_addr shall be ignored.

bzero – memory operations (LEGACY)

The bzero() function shall place n zero-valued bytes in the area pointed to by s.

bcopy - memory operations (LEGACY)

The bcopy() function shall copy n bytes from the area pointed to by s1 to the area pointed to by s2. The bytes are copied correctly even if the area pointed to by s1 overlaps the area pointed to by s2.