Sie sind auf Seite 1von 48

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Laboratory Name : Network Laboratory Subject Code : CS1305

Ex.No 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.

NAME OF THE PROGRAM Simulation of Address Resolution Protocol (ARP) / Reverse Address Resolution Protocol (RARP). Implementation of bit stuffing and CRC Computation. File Transfer Protocol Using RS232 Interface. Simulation of Sliding-Window protocol. Implementation of Open Shortest Path Finding (OSPF)/ Border Gateway Protocol (BGP) routing protocols Client Server Chat using TCP / IP. TCP Connection Establishment. UDP Connection Establishment. Domain Name System Implementation. Download a file from a HTTP Server. Study of Network Simulator (NS2)

1. IMPLEMENTATION OF ARP/RARP
Aim To 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);

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

Output $ cc arp2.c $./a.out 1. Server mode 2. Client mode Enter your choice : 1 Welcome to server mode Enter the logical IP and physical address 192.168.1.1 45.21.BD.F2.23.FF $ ./a.out 1. Server mode 2. Client mode Enter your choice : 2 Welcome to client mode 1. Logical IP to MAC 2. MAC to logical IP Enter your choice : 1 Enter the logical IP : 192.168.1.1 The physical address : 45.21.BD.F2.23.FF $ ./a.out 1. Server mode 2. Client mode Enter your choice : 2 Welcome to client mode 1. Logical IP to MAC 2. MAC to logical IP Enter 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.

2 (a) IMPLEMENTATION OF BIT STUFFING


Aim To write a C program to implement the bit stuffing. Theory In 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;

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.out Enter the input bit sequence : 111111111111111111111111 $ Stuffed bit sequence : 1111101111101111101111101111 Destuffed bit sequence : 111111111111111111111111 Result Thus the C program to implement bit stuffing is written, entered, executed and results are verified.

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. 2. 3. 4. 5. Start the program. Get the generator bits and data bits from the user. Find the length of the generator and data bits. Append [length of generator -1] 0s in data bits. 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 10 void 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'; } }

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

Enter the generator bits : 1101 Enter the data bits to be transmitted : 100100000 Generator : 1101 Data : 100100000 CRC : 101 Transmitted bits : 100100000101 Enter the Received bits : 100100000101 Received bits : 100100000101 Remainder : 000 Hence 100100000101 is received Accepted Data bits : 100100000 Enter the Received bits : 100100010101 Received bits : 100100010101 Remainder : 111 Hence 100100010101 is received Rejected Result Thus the C program to implement Cyclic Redundancy Check is written, entered, executed and results are verified.

3. FILE TRANSFER USING RS-232 INTERFACING


Aim 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 Circuitterminating 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 1 2 3 4 5 6 7 8 9 10 PIN NUMBER 1 2 3 4 5 6 7 8 20 22 SIGNAL --TXD RXD RTS CTS DSR SG RLSD or CD DTR RI SIGNAL NAME Frame ground Transmit data Receive data Request to send Clear to send Data Set Ready Signal Ground Received line signal detect or carrier detect Data Terminal Ready Ring Indicator

Algorithm Server 1. Start the program 2. Include the necessary files and declare the necessary variables 3. 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 1. Start the program 2. 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 clients 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 5 void 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; 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):1 Enter the file name to be sent : vijay Vijay Karthi Kathir # File sent Successfully Receiver:

Select: Send/Receive (1/2):2 Enter the file name to be received : vijay Vijay Karthi Kathir # 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.

4. A. SLIDING WINDOW PROTOCOL - GO BACK N


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

Use of piggybacking 1 When traffic is bi-directional RNs are piggybacked on packets going in the other direction Each packet contains a SN field indicating that packets 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>

#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"); else if(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

{ 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); } else printf("\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();} } } Output Enter how many frames:5 Enter the data:1 2 3 4 5 Enter which frame received with error Enter -1 if no frame received with error:-1 All frames received correctly

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

4. B. SLIDING WINDOW PROTOCOL - SELECTIVE REPEAT ARQ


Aim To write a C program to implement sliding window protocol using selective repeat ARQ. Theory 1 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 3 SRP 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 unACKed 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.

Program 5 #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); }

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(); } } Output enter how many frames : 3 enter the data 123 enter which frame recd with error enter -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 correctly frame 2 is recd correctly frame 3 is recd correctly ack is sent for frame 29659 ack is sent for frame 147 ack is sent for frame 19460 Result Thus a C program to implement sliding window protocol using selective repeat ARQ is written, entered, executed and output is verified.

5. SHORTEST PATH CALCULATION IN OSPF


Aim To 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 unknown 2. Tentative distance dv, from a source to a vertex, is kept 3. Known vertices is determined by the distance that turns out to be the shortest path length 4. Select a vertex v, which has the smallest path dv among all the unknown vertices 5. Declare the shortest path from source to vertex to known 6. The remainder of a stage consists of updating the values of adjacent distance dw 7. 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++)

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

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

Output ENTER THE NO. OF VERTICES 3 ENTER THE DIRECTED ADJACENCY MATRIX 3 1 2 3 4 5 6 7 8 THE MATRIX IS

3 1 2 3 4 5 6 7 8 ENTER THE STARTING NODE 1 PREDECESSOR 1 1 1 DISTANCE 0 1 2 ENTER THE DESTINATION VERTEX 3 SHORTEST 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.

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

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

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;

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

if(!strcmp(content,"exit")) { printf("\nUser in exit mode"); exit(0); } } } close(clisock); } Output $ ./server.out Hi How are you? Other user wants to quit $ ./client.out Hi How are you? Data Transmission exit User in exit mode Result Thus the C program for client-server chat using TCP is written, entered, executed and the results are verified.

7. TCP CONNECTION ESTABLISHMENT


Aim To 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 wont 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. Receive data from client by using recv() and print it. 8. Close all open sockets. 9. Stop the program.

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

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

{ 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.out Client Module: Hi Data Transmission $ ./server.out Server 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.

8. UDP CONNECTION ESTABLISHMENT


Aim To 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.

4. 5. 6. 7.

Initialize the client socket structure variable cli_ip(family, port & address). Send data to the server using sendto(). Close all open sockets. 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>

#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.out Networks Data Transmitted to the server : Networks $ ./udpserver.out Before Socket creation After Socket creation Before bind After bind Data 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.

9. DOMAIN NAME SYSTEM IMPLEMENTATION


Aim To 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 machines 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 space 2. Hierarchical Name space The 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 Resolution 2. Iterative Resolution An example of domain name is www.google.com, www.klnce.edu. Algorithm Server 1. Start the program 2. 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 client 9. 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().

6. 7. 8. 9.

Send the domain name to be resolved to the DNS Server using send(). Receive the reply from the server and print it. Close all open sockets. 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);

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

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.out Client Module Enter the domain name : www.google.com 205.209.50.70 $ ./dnss.out Server Module ****************** RECEIVING The cmp value is 1 match Result Thus the C program to resolve a domain name using DNS Server is written, entered, executed and the results are verified.

10. DOWNLOAD A FILE FROM A HTTP SERVER


Aim To 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. GET 2. PUT 3. HEAD 4. POST 5. COPY 6. DELETE 7. 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 files contents. 9. Close all open sockets. 10. Stop the program.

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

printf("Received:%s",buf); } close(sockfd); } Output $ ./a.out Received:HTTP/1.0 302 Found Location: http://www.google.co.in/ Cache-Control: private Content-Type: text/html; charset=UTF-8 Set-Cookie: PREF=ID=6de4506bfc45c567:TM=1255516287:LM=1255516287:S=x4Kpx6GNDP1po QXy; expires=Fri, 14-Oct-2011 10:31:27 GMT; path=/; domain=.google.com Set-Cookie: NID=27=J3r4GdeIut3M4VgvMeGVRLCX8MKt10T1UU9lztVWPwS5OyvLvTTdzZx54 OzGG1DV8OCxurf6nuG9cz9rVEcb79gSudbA7k50Sr63K2BBUQc4IpKcvUWxiJue0_A 5IXgv; expires=Thu, 15-Apr-2010 10:31:27 GMT; path=/; domain=.google.com; HttpOnly Date: Wed, 14 Oct 2009 10:31:27 GMT Server: gws Content-Length: 221 X-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.

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 Dijikstras and more. NS also implements multicasting and same of the MAC layer protocols for LAN situations. Simplified Users view of NS In a simplified users 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.

#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 queuelimit $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

# Setup a FTP over TCP connection set 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

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 connectionlessmode 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 connectionlessmode socket. It is normally used with connectionless-mode sockets because it permits the application to retrieve the source address of received data.

sendto - send a message on a socket The sendto() function shall send a message through a connection-mode or connectionlessmode 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.