CS2307 - Network Lab Manual(2)

86
LAB MANUAL Sub Code :- CS2307 Sub Name :- Network Lab Branch :- COMPUTER SCIENCE AND ENGINEERING Semester :- 05 LIST OF EXPERIMENTS CS2307 - NETWORK LAB 1. Study of Network Commands 2a. Using TCP SOCKETS ( DATE TIME SERVER & CLIENT ) 2b. Using TCP SOCKETS ( ECHO SERVER & CLIENT) 2c.Using TCP SOCKETS ( TCP CHAT ) 3a. Using UDP SOCKETS ( RESOLVING THE DNS SERVER USING UDP ) 3b.USING SOCKETS ( DOMAIN NAME SERVER ) 4. Using RAW Sockets ( Packet Capturing And Filtering) 5. Programs Using RPC 6. Simulation of Sliding Window Protocols ( NS2 simulators) 7. Implementing Routing Protocols (OSPF ,DSDV) 1

Transcript of CS2307 - Network Lab Manual(2)

Page 1: CS2307 - Network Lab Manual(2)

LAB MANUAL

Sub Code :- CS2307

Sub Name :- Network Lab

Branch :- COMPUTER SCIENCE AND ENGINEERING

Semester :- 05

LIST OF EXPERIMENTS

CS2307 - NETWORK LAB

1. Study of Network Commands

2a. Using TCP SOCKETS ( DATE TIME SERVER & CLIENT )

2b. Using TCP SOCKETS ( ECHO SERVER & CLIENT)

2c.Using TCP SOCKETS ( TCP CHAT )

3a. Using UDP SOCKETS ( RESOLVING THE DNS SERVER USING UDP )

3b.USING SOCKETS ( DOMAIN NAME SERVER )

4. Using RAW Sockets ( Packet Capturing And Filtering)

5. Programs Using RPC

6. Simulation of Sliding Window Protocols ( NS2 simulators)

7. Implementing Routing Protocols (OSPF ,DSDV)

8. Performance Comparison of MAC protocols

9. Performance comparison of Routing Protocols

10. Study of UDP performance

11. Study of TCP Performance

1

Page 2: CS2307 - Network Lab Manual(2)

REQUIREMENTS

1. SOFTWARE

C++ Compiler J2SDK (freeware) Linux NS2/Glomosim/OPNET

(Freeware)

2. HARDWARE

PCs

2

Page 3: CS2307 - Network Lab Manual(2)

INDEX

S.NO EXPRIMENT NAME

1. Study of Network Commands

2a. Using TCP SOCKETS ( DATE TIME SERVER & CLIENT )

2b. Using TCP SOCKETS ( ECHO SERVER & CLIENT)

2c. Using TCP SOCKETS ( TCP CHAT )

3a. Using UDP SOCKETS ( RESOLVING THE DNS SERVER USING UDP )

3b. USING SOCKETS ( DOMAIN NAME SERVER )

4. Using RAW Sockets ( Packet Capturing And Filtering)

5. Programs Using RPC

6. Simulation of Sliding Window Protocols ( NS2 simulators)

7. Implementing Routing Protocols (OSPF ,DSDV)

8. Performance Comparison of MAC protocols

9. Performance comparison of Routing Protocols

10. Study of UDP performance

11. Study of TCP Performance

3

Page 4: CS2307 - Network Lab Manual(2)

EX.No:1 STUDY OF NETWORK COMMANDS

1. SOCKET FUNCTION

Int Socket(int family , int type , int protocol);

It returns non negative value if ok, -1 on error.

FAMILY DESCRIPTION

AF_INET

AF_INET6

Ipv4 Protocol

Ipv6 Protocol

TYPE DESCRIPTION

Sock_STREAM

Sock_DGRAM

Sock_RAW

Stream socket- TCP

Datagram socket-UDP

Raw socket-Ipv4, Ipv6

2. CONNECT FUNCTION:

Int connect(int sockfd, const struct sockaddr * sockaddr, socklen_t addrlen);

Returns 0 if ok, -1 on error.

- It is used to client to establish a connection with a TCP server.

4

Page 5: CS2307 - Network Lab Manual(2)

3. BIND FUNCTION

Int bind(int sockfd, const struct sockaddr *myaddr, socklen_t_addrlen);

Returns 0 if ok, -1 on error.

- It assigns a local protocol address to a socket

- second argument is a pointer to a protocol specific address

- third argument is the size of this address structure

- calling bind let us specify a port number an IP address, both or

neither.

4. LISTEN FUNCTION It will called only by a TCP server.

Int listen(int sockfd, int backlog);

- When a socket is created by the socket function, a client socket

will issue a connect. The listen function converts an

unconnected socket in to passive socket.

- The second argument to this function specifies the maximum

number of connections that the kernel should queue for this

socket.

5. CLOSE FUNCTION:Int close(int sockfd)

- The default action of close with a TCP socket is to mark the

socket as closed and return to the process immediately.

5

Page 6: CS2307 - Network Lab Manual(2)

EX.NO:- 2a DAY AND TIME OF SERVER

AIM:

To display the day and time of the server using Telnet.

ALGORITHM:

SERVER:

1) Start the program.2) Create a socket with address family AF_INET type SOCK_STREAM family

and default protocol.3) Initialise the socket and set its attributes and assign a specific port number as

desired4) Bind the server to the socket using Bind function.5) Wait for the client requests . On request establish a connection using accept

function.6) Send the day and time to the client.7) Repeat the steps until the connection is terminated.8) Stop the program.

CLIENT:

1) Start the program.

2) Create a socket with address family AF_INET type SOCK_STREAM family and default protocol.

3) Initialise the socket and set its attributes and assign a specific port number as desired

4) Connect to the server using connect function to initialise the request.5) Receive day and time from the server.6) Repeat the steps until the connection is terminated.7) Stop the program.

6

Page 7: CS2307 - Network Lab Manual(2)

CLIENT PROGRAM:-

#include<stdio.h>#include<stdlib.h>#include<sys/socket.h>#include<sys/types.h>#include<netdb.h>int main(){int sd,c;char msg[50],sip[15];struct sockaddr_in caddr;struct hostent *he;printf("enter server IP address");scanf("%s",sip);he=gethostbyname(sip);sd=socket(AF_INET,SOCK_STREAM,0);if(sd!=-1)printf("socket is created\n");elseprintf("socket is no created\n");caddr.sin_family=AF_INET;caddr.sin_port=htons(5666);c=connect(sd,(struct sockaddr *)&caddr,sizeof(caddr));if(c==0)printf("connected to server");elseprintf("not connected");recv(sd,msg,sizeof(msg),0);printf(" the day and time of the server is %s",msg);close(sd);return 0;}

7

Page 8: CS2307 - Network Lab Manual(2)

SERVER PROGRAM:-

#include<stdio.h>#include<string.h>#include<stdlib.h>#include<sys/socket.h>#include<sys/types.h>#include<netinet/in.h>#include<unistd.h>int main(){int sd,b,cd;char msg[50];struct sockaddr_in caddr,saddr;socklen_t clen=sizeof(caddr);time_t tick;sd=socket(AF_INET,SOCK_STREAM,0);if(sd!=-1)printf("socket is created\n");elseprintf("socket is not created\n");saddr.sin_family=AF_INET;saddr.sin_addr.s_addr=htonl(INADDR_ANY);saddr.sin_port=htons(5666);b=bind(sd,(struct sockaddr *)&saddr,sizeof(saddr));if(b==0)printf(“bind to client:\n”);elseprintf(“not bind to client:\n”);listen(sd,5);while(1){cd=accept(sd,(struct sockaddr *)&caddr,&clen);tick=time(NULL);printf("system day and time %s",ctime(&tick));strcpy(msg,ctime(&tick));send(cd,msg,sizeof(msg),0);}close(sd);close(cd);return 0;

}

8

Page 9: CS2307 - Network Lab Manual(2)

OUTPUT:-SERVER:-

[vt4862@localhost ~]$ cc sday.c [vt4862@localhost ~]$ ./a.out socket is created binded to client system day and time:Fri Mar 6 15:17:26 2009

CLIENT:-

[vt4862@localhost ~]$ cc cday.c[vt4862@localhost ~]$ ./a.out

enter ip address:100.30.20.10

9

Page 10: CS2307 - Network Lab Manual(2)

socket is created connected to server the day and time erver is Fri Mar 6 15:17:26 2009[vt4862@localhost ~]$

RESULT:- Thus the day time server is executed and the output is verified.

EX.NO:- 2b TCP – SIMPLE MESSAGE PASSING

AIM: To enable a simple message passing between client and server.

ALGORITHM: SERVER:

1) Start the program.2) Create a socket with address family AF_INET type SOCK_STREAM

family and default protocol.3) Initialise the socket and set its attributes and assign a specific port

number as desired4) Bind the server to the socket using Bind function.5) Wait for the client requests . On request establish a connection using

accept function.6) Fork a child process perform steps 7-10 for each process.7) Read the message from the client through the connection.8) Display the client’s message9) Send an acknowledgement message to the client.10) Exit the child process and close the connection.

CLIENT:1) Start the program.2) Create a socket with address family AF_INET type SOCK_STREAM

family and default protocol.3) Initialise the socket and set its attributes and assign a specific port

number as desired4) Connect to the server using connect function to initialise the request.5) Send the message to the server.6) Receive an acknowledgement from the server.7) Stop the program.

10

Page 11: CS2307 - Network Lab Manual(2)

PROGRAM:

Server

#include<stdio.h>#include<sys/types.h>#include<sys/socket.h>#include<netinet/in.h>#include<netdb.h>#define SERV_PORT 5001int main(int argc,char* argv[]){int sockfd,newsockfd,clen;struct sockaddr_in serv_addr,cli_addr;char buffer[4096];sockfd=socket(AF_INET,SOCK_STREAM,0);serv_addr.sin_family=AF_INET;serv_addr.sin_addr.s_addr=INADDR_ANY;serv_addr.sin_port=htons(SERV_PORT);bind(sockfd,(struct sockaddr*)&serv_addr,sizeof(serv_addr));listen(sockfd,5);clen=sizeof(cli_addr);newsockfd=accept(sockfd,(struct sockaddr*)&cli_addr,&clen);bzero(buffer,4096);read(newsockfd,buffer,4069);printf("\n Client:%s",buffer);write(newsockfd,buffer,4069);printf("\n");close(sockfd);return(0);}

11

Page 12: CS2307 - Network Lab Manual(2)

Client

#include<stdio.h>#include<sys/types.h>#include<sys/socket.h>#include<netinet/in.h>#include<netdb.h>#define SERV_PORT 5001int main(int argc,char* argv[]){int sockfd;struct sockaddr_in serv_addr;struct hostent *server;char buffer[4096];sockfd=socket(AF_INET,SOCK_STREAM,0);serv_addr.sin_family=AF_INET;serv_addr.sin_addr.s_addr=inet_addr("30.29.28.200");serv_addr.sin_port=htons(SERV_PORT);connect(sockfd,(struct sockaddr*)&serv_addr,sizeof(serv_addr));printf("\nEnter your message to send....\n");bzero(buffer,4096);printf("\nclient:");fgets(buffer,4096,stdin);write(sockfd,buffer,4096);bzero(buffer,4096);read(sockfd,buffer,4069);printf("\n Server message :%s",buffer);printf("\n");close(sockfd);return(0);}

12

Page 13: CS2307 - Network Lab Manual(2)

OUTPUT

SERVER SIDE:

[vt4802@localhost ~]$ ./a.out

client:hai

CLIENT SIDE:

[vt4802@localhost ~]$ ./a.out

enter ur msg to send.......

13

Page 14: CS2307 - Network Lab Manual(2)

client:hai server msg:hai

RESULT:

Thus the program for Simple message passing using TCP was successfully executed and verified.

EX.NO:- 2c TCP – SIMPLE CHAT (HALF DUPLEX)

AIM: To enable chatting between the client and server.

ALGORITHM:

SERVER:1) Start the program.2) Create a socket with address family AF_INET type SOCK_STREAM family

and default protocol.3) Initialise the socket and set its attributes and assign a specific port number as

desired4) Bind the server to the socket using Bind function.5) Establish the listen queue using the listen function.6) Wait for the client requests . On request establish a connection using accept

function.7) Repeat the steps 8-10 until the server sends “bye”.8) Read the message from the client through the connection using read function

and display the client’s message9) If the client message is “bye” goto step 11.10) Accept the server message and write it to the client using write function.11) Close the connection.12) Goto step 6.

CLIENT:1) Start the program.2) Create a socket with address family AF_INET type SOCK_STREAM family

and default protocol.3) Initialise the socket and set its attributes and assign a specific port number as

desired4) Connect to the server using connect function to initialise the request.5) Repeat the steps 6-8 until the server sends “bye”6) Accept the client message and write it to the server using write function.

14

Page 15: CS2307 - Network Lab Manual(2)

7) If the client message is “bye” goto step 9.8) Read the message using read function and display the message9) Stop the program.

PROGRAM:

Server

#include<stdio.h>#include<sys/types.h>#include<sys/socket.h>#include<netinet/in.h>#include<netdb.h>#define SERV_PORT 5001int main(int argc,char* argv[]){

int sockfd,newsockfd,clen;struct sockaddr_in serv_addr,cli_addr;char buffer[4096];sockfd=socket(AF_INET,SOCK_STREAM,0);serv_addr.sin_family=AF_INET;serv_addr.sin_addr.s_addr=INADDR_ANY;serv_addr.sin_port=htons(SERV_PORT);{ind(sockfd,(struct sockaddr*)&serv_addr,sizeof(serv_addr));listen(sockfd,5);clen=sizeof(cli_addr);newsockfd=accept(sockfd,(struct sockaddr*)&cli_addr,&clen);do{

bzero(buffer,4096);read(newsockfd,buffer,4096);}rintf("\n Client Message: %s",buffer);bzero(buffer,4096);printf("Server Message:");fgets(buffer,4096,stdin);write(newsockfd,buffer,4096);

}while(strcmp(buffer,"bye\n")!=0);close(sockfd);

15

Page 16: CS2307 - Network Lab Manual(2)

return(0);}

Client

#include<stdio.h>#include<sys/types.h>#include<sys/socket.h>#include<netinet/in.h>#include<netdb.h>#define SERV_PORT 5001int main(int argc,char* argv[]){

int sockfd;struct sockaddr_in serv_addr;struct hostent *server;char buffer[4096];sockfd=socket(AF_INET,SOCK_STREAM,0);serv_addr.sin_family=AF_INET;serv_addr.sin_addr.s_addr=inet_addr("30.29.28.200");serv_addr.sin_port=htons(SERV_PORT);connect(sockfd,(struct sockaddr*)&serv_addr,sizeof(serv_addr));do{

bzero(buffer,4096);printf("\nClient Message:");fgets(buffer,4096,stdin);write(sockfd,buffer,4096);bzero(buffer,4096);read(sockfd,buffer,4096);printf("\n Server Message :%s",buffer);

}while(strcmp(buffer,"bye\n")!=0);close(sockfd);return(0);

}

16

Page 17: CS2307 - Network Lab Manual(2)

OUTPUT: SERVER SIDE:

[vt4862@localhost ~]$ ./a.out

client message:hi server:hello how are youclient message:am fine server:ok take careclient message:bye server:bye

[vt4862@localhost ~]$

CLIENT SIDE:

[vt4862@localhost ~]$ ./a.out

client:hi server message:hello how are you

17

Page 18: CS2307 - Network Lab Manual(2)

client:am fineserver message:ok take care client:byeserver message:bye

[vt4862@localhost ~]$

RESULT:Thus the program for TCP Simple chat is executed and output is verified.

EX.NO:- 3a) UDP SOCKETS ( RESOLVING THE DNS SERVER USING UDP)

AIM: To implement the resolving of hostname by a DNS server.

ALGORITHM:

1) Start the program.2) Obtain the service name and protocol.3) Enter the port number and address type.4) Similarly follow the above step once again.5) The subsequent steps makes the required output to be displayed on the output

screen.6) The output is verified after executing the program.7) Stop the program.

PROGRAM:

#include<netdb.h>main(){

struct servent *sptr;int port;char pro[100],name[100];printf("Enter the ser name:");scanf("%s",name);printf("\n Enter the protocol(UDP/TCP):");scanf("%s",pro);sptr=getservbyname(name,pro);printf("\n port no:%d",sptr->s_port);printf("\n address:%s",sptr->s_name);printf("enter the service port no");scanf("%d",&port);printf("Enter the protocol(UDP/TCP):");

18

Page 19: CS2307 - Network Lab Manual(2)

scanf("%s",pro);sptr=getservbyport(htons(port),pro);printf("\n port no:%d",sptr->s_port);printf("\n addr:%s",sptr->s_name);printf("\n protocol:%s",sptr->s_proto);

}

Output:

[vt4862@localhost ~]$ cc adns.c[vt4862@localhost ~]$ ./a.out a.txt enter service namehttp enter the protocol (UDP/TCP)tcp portno:20480 address:http enter the service port no80

19

Page 20: CS2307 - Network Lab Manual(2)

enter protocol (UDP/TCP)tcp port no:20480 address:http protocol:tcp[vt4862@localhost ~]$

Result:

Thus the resolver server using domain name space is executed and the output is verified.

EX.NO:- 3b) DOMAIN NAME SERVER USING UDP

AIM: To implement Domain Name Server using UDP client- server program.

ALGORITHM: SERVER:

1) Start the program.2) Create a socket with address family AF_INET type SOCK_STREAM

family and default protocol.3) Assign IP address, port number and protocol family to the members.4) Bind the IP address, port number and protocol family to the socket.5) Listen for requests from client.6) Obtain the hostname and retrieve address using gethostbyname

function.7) Write the host address to the client side.8) Close the socket.

CLIENT: 1) Start the program.2) Create a socket with address family AF_INET type SOCK_STREAM

family and default protocol.

20

Page 21: CS2307 - Network Lab Manual(2)

3) Initialize the socket and its attributes.4) Enter the hostname and write it to the server.5) Read the IP address and display it.6) Close the socket.

PROGRAM:-

SERVER:-

#include<netinet/in.h>#include<stdio.h>#include<string.h>#include<arpa/inet.h>#include<sys/types.h>#include<netdb.h>#include<sys/socket.h>int main(int argc,char *argv[]){int sockfd,n;char msg[1024],buf[1024];struct sockaddr_in servaddr,cliaddr;socklen_t len;struct hostent *hp;sockfd=socket(AF_INET,SOCK_DGRAM,0);bzero(&servaddr,sizeof(servaddr));servaddr.sin_family=AF_INET;servaddr.sin_addr.s_addr=htonl(INADDR_ANY);servaddr.sin_port=htons(4773);bind(sockfd,(struct sockaddr*)&servaddr,sizeof(servaddr));for(;;)

21

Page 22: CS2307 - Network Lab Manual(2)

{len=sizeof(cliaddr);n=recvfrom(sockfd,msg,100,0,(struct sockaddr*)&cliaddr,&len);msg[n]='\0';printf("%s\n",msg);if(n<0){perror("Send error");}if((hp=gethostbyname(msg))==NULL){printf("cant get address");}if(inet_ntop(AF_INET,hp->h_addr_list[0],buf,sizeof(buf))<=0)printf("Host address not available\n");printf("%s",buf);sendto(sockfd,buf,sizeof(buf),0,(struct sockaddr*)&cliaddr,len);}}

CLIENT:-

#include<netinet/in.h>#include<strings.h>#include<arpa/inet.h>#include<netdb.h>#define MAXLINE 1024int main(int argc,char *argv[]){int sockfd,n;socklen_t len;char sendline[1024],recvline[1024];struct sockaddr_in servaddr;scanf("%s",sendline);sockfd=socket(AF_INET,SOCK_DGRAM,0);bzero(&servaddr,sizeof(servaddr));servaddr.sin_family=AF_INET;servaddr.sin_port=htons(4773);inet_pton(AF_INET,argv[1],&servaddr.sin_addr);len=sizeof(servaddr);sendto(sockfd,sendline,strlen(sendline),0,(struct sockaddr*)&servaddr,len);n=recvfrom(sockfd,recvline,MAXLINE,0,NULL,NULL);recvline[n]='\0';

22

Page 23: CS2307 - Network Lab Manual(2)

printf("\nThe IPaddress is %s",recvline);return 0;}

OUTPUT:-

SERVER:-

[vt4795@localhost kanna]$ ./a.out 100.30.20.10100.30.20.10

[vt4795@localhost kanna ]$

CLIENT:-

23

Page 24: CS2307 - Network Lab Manual(2)

[vt4795@localhost kanna]$ cc dnsclient.c[vt4795@localhost kanna]$ ./a.out redhat 100.30.20.10100.30.20.10

The IP address is 100..30.20.10 [vt4795@localhost kanna]$

RESULT:- Thus the Domain name server using UDP is executed and output is verified.

DNSPROGRAM

#include<stdio.h>#include<sys/socket.h>#include<sys/types.h>#include<netdb.h>#include<string.h>#include<arpa/inet.h>#include<netinet/in.h>#include<stdlib.h>

int main(int argc,char *argv[]){char *ptr,**pptr;char str[INET6_ADDRSTRLEN];struct hostent *hptr;

while(argc > 0){ptr=argv[1];if((hptr=gethostbyname(ptr))==NULL){continue;

24

Page 25: CS2307 - Network Lab Manual(2)

}printf("Official Host have:%s\n",hptr->h_name);

switch(hptr->h_addrtype){case AF_INET:

pptr=hptr->h_addr_list;for(;*pptr!=NULL;pptr++)printf("Address:%s\n",inet_ntop(hptr->h_addrtype,*pptr,str,sizeof(str)));exit(0);break;

default:break;

}}exit(0);

}

OUTPUT

Official Host have:localhost.localdomain

Address:127.0.0.1

25

Page 26: CS2307 - Network Lab Manual(2)

RESULT:-

Thus the Domain name server using UDP is executed and output is verified.

EX.NO:- 4 RAW SOCKETS

4a)

Aim :- To implement Socket Creation

Algorithm:

Step1: Start the program Step2:Declare two integers socket fd1,fd2Step3:Define sockfd socket which transmit data as stream of bytes.Step4:-Define sockfd2 as socket which transmit data as datagramStep5: If socket fd is -1 then display socket 1 is not created Step6: If sockfd2 is -1 then display socket 2 is not created else obtain file descriptorStep7:Stop the Program.

PROGRAM:-

#include<stdio.h>#include<stdlib.h>#include<sys/socket.h>#include<netinet/in.h>#include<arpa/inet.h>#include<unistd.h>

26

Page 27: CS2307 - Network Lab Manual(2)

{printf(“\n Socket Creation”);int sockfd1,sockfd2;sockfd1=socket(AF_INET,SOCK_STREAM,0);sockfd2=socket(AF_INET,SOCK_STREAM,0);if(sockfd1==-1){ printf(”\nSocket is not created”);}

else{

prints(“\nSocket1 is not created”);printf(“\n socket1 file descriptor is “ %d,sockfd1);

}if(sockfd2==-1){

printf(“\n cokcet1 is not created”);}

else{

printf(“\n socket is created”);printf(“\n socket2 file descriptor is :%d,sockfd2);

}}

OUTPUT

SOCKET CREATION

Socket1 is created

Socket1 file descriptor is :3

Socket2 is created

Socket2 file descriptor is :3

27

Page 28: CS2307 - Network Lab Manual(2)

Result :- Thus Socket has been created successfully

Ex.No :- 4b SOCKET BINDING

Aim: To implement Socket Binding

Algorithm:

Step1: Start the program Step2: Define the portno globally as 2000Step3:Declare the initial variable sockfd1Step4:Define the structure for both client and serverStep5:If sockfd is transmitted as stream of bytes it is equal to -1 then display “ Error Message”Step6:Using the member fun access the structure value such as sin_family,sin_port,sin_addrStep7:If size of bind value is not -1 then display socket bounded portno else display Bind errorStep8: Stop the Program.

Program:

28

Page 29: CS2307 - Network Lab Manual(2)

#include<stdio.h>#include<stdlib.h>#include<sys/socket.h>#include<netinet/in.h>#include<arpa/inet.h>#include<unistd.h>#defibe PORTNO 2000

int main(){printf(“\n Socket Binding”);int sockfd,i=PORTNO;struct sockaddr_in myaddr;if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1){printf(“\n socket creation error);}myaddr.sin_family=AF_NET;myaddr.sin_port=htone(PORTNO);myaddr.sin_addr.s_addr=INADDR_ANY;

memset(&(myaddr.sin_zero,’\0’,8));if(bind(sockfd,(struct sockaddr*)&mytaddr,sizeof(myaddr))!=-1){

printf(“\nsocket is binded to port number %d”,i);}else{printf(“\n binding error”);}}

OUTPUT

Socket binding

Socket bounded to port number 2000

29

Page 30: CS2307 - Network Lab Manual(2)

Result :- Thus Socket has been Binding successfully

EX.NO:-5 RPC

AIM :-

To implement Remote Procedure Call.

ALGORITHM:-

Step1:Start the programStep2:create a remote interfaceStep3:create implementation for remote methods.Step4:Generating stub abd skeleton classes using rmi complierStep5:The client classfile,the stub classfile and the interface class files are placed on client machine.Step6:The server classfile,interface classfile and the skeleton classfile placed on server machine.Step7:Create an instance of Remote object Step8:Create an instance of Remote object.Step9:Register the Remote objectStep10:Invoke the Remote Methods

30

Page 31: CS2307 - Network Lab Manual(2)

Step11:Stop the program

PROGRAM:-

/* INTERFACE PROGRAM*/

import java.rmi.*;

public interface SerInt extends Remote{double add(double d1,double d2)throwa RemoteExecution;}

/* ADDSERVER IMPLEMENTATION PROGRAM*/

import java.rmi.*;import java.rmi.server.*;public class AddServerimpl extends UnicastRemoteObject implements server{public Addserverimpl() throws RemoteException{}public double add(double d1,double d2) throws RemoteException{return d1+d2;}}

/* ADDSERVER PROGRAM */

import java..rmi.*;import java.rmi.registry.*;public class AddServer

{

public static void main(String arg[]){

31

Page 32: CS2307 - Network Lab Manual(2)

try{

AddServerimpl asim=new AddServerimpl();Registry reg=LocateRegistry.createRegistry(5000);Reg.rebind(“AddServer”,asim);System.out.println(“Server start…”);String ab[]=reg.list();System.out.println(“the remote object available are “);For(int i=0;i<ab.length;i++)System.out.println(ab[i]);}catch(Exception e){System.out.println(“Exception “ +e);

} }}

/* ADDCLIENT PROGRAM */

import java.rmi.*;public class AddClient

public static void main(String args[]){try{SerInt adInt=(SerInt)Naming.lookup(“rmi://localhost:5000/AddServer”);System.out.println(“The first number is”+args[0]);Double d1=Double.valueOf(args[0].doubleValue();System.out.println(:the second number is : “+args[1]);double d2=double.ValueOf(args[1].doubleValue();System.out.println(“The sum is :”+adint.add(d1,d2));}catch(Exception e){System.out.println(“Exception : “+e);}

}OUTPUT

C:\jdk1.3>javac SerInt.javaC:\jdk1.3\bin>javac AddServerimpl.java

32

Page 33: CS2307 - Network Lab Manual(2)

C:\jdk1.3\bin>rmic AddServerimplC:\jdk1.3\bin>javac AddServer.javaC:\jdk1.3\bin>java AddServer

Server start…..The remote objects available are :AddSErver

C:\jdk1.3\bin>javac AddClient.javaC:\jdk1.3\bin>java AddClient 1 2

The First number is : 1The Second number is : 2The Sumis : 3.0

RESULT:Thus the program for implementing RMI/RPC executes successfully.

EX.NO:- 6 SLIDING WINDOW PROTOCOL

AIM : To avoid congestion and to ensure reliable data transfer.

ALGORITHM: 1) Start the program 2) Sender keeps track of outstanding frames and updates the variables and window as acknowledgements arrive. 3) Receiver sliding window waits for a specific frame to arrive in a specific order and frame arriving out of order is discarded and needs to be resent . 4) Commence transmission. 5) Deal with damaged or lost frame. 6) Deal with damaged or lost acknowledgement. 7) Deal with delayed acknowledgement. 8) Update sender window size. 9) Stop the program. PROGRAM:#include<stdio.h>

33

Page 34: CS2307 - Network Lab Manual(2)

#include<conio.h>#include<stdlib.h>void main(){int temp1,temp2,temp3,temp4;int winsize=8;int noframes,moreframes,i;int receiver(int);int simulate(int);temp1=0;temp2=0;temp3=0;temp4=0;clrscr();for(i=0;i<200;i++)rand();noframes=5;printf("\nNo. of frames is %d",noframes);getch();moreframes=noframes;while(moreframes>0){temp1=simulate(winsize);winsize=temp1;temp4+=temp1;if(temp4>noframes)temp4=noframes;for(i=temp3+1;i<=temp4;i++)printf("\nSending frame %d",i);getch();temp2=receiver(temp1);temp3+=temp2;if(temp3>noframes)temp3=noframes;printf("\nAcknowledgement for the frames upto %d",temp3);getch();moreframes-=temp2;temp4=temp3;if(winsize<=0)winsize=8;}printf("\nEnd of SLIDING WINDOW PROTOCOL");getch();}int receiver(int temp1){

34

Page 35: CS2307 - Network Lab Manual(2)

int i;for(i=0;i<100;i++)rand();i=rand()%temp1;return 1;}int simulate(int winsize){int temp1,i;for(i=0;i<50;i++)temp1=rand();if(temp1==0)temp1=simulate(winsize);i=temp1%winsize;if(i==0)return winsize;elsereturn temp1%winsize;}

OUTPUT:

SENDING FIRST FRONE......1 sending1Ack(NEXT EXPECTEd FRAME)::2 sending2Ack(NEXT EXPECTEd FRAME)::3 sending3Ack(NEXT EXPECTEd FRAME)::4SENDING......4SENDING......5SENDING......6SENDING......7

TIMEOUT.FOR FRAME4

Resending.....4Resending.....5Resending.....6Resending.....7

35

Page 36: CS2307 - Network Lab Manual(2)

RESULT:

Thus the program to do the SLIDING WINDOW PROTOCOL was executed and output was verified.

EX.NO:-7a ROUTING PROTOCOL (OSPF)

AIM: To find the shortest path on interior routing protocol based on link state routing Update table inside autonomous systems.

ALGORITHM: 1) Start the program. 2) Use the link state routing to update the routing table area. 3) Each router sends the state of its neighbourhood to every other router it does so by flooding. 4) Each neighbour sends the packet to all its neighbours. 5) Each router shares the state of its neighbourhood only when there is a change. 6) From this router calculate the shortest path between itself and each in the network. 7) Stop the program.

PROGRAM;-

#include<stdio.h>#include<conio.h>#define INFIN 999

36

Page 37: CS2307 - Network Lab Manual(2)

typedef struct edge{int wt;}edge;edge connection[10][10];int n;void main(){int perm[10];int source,dest,i,j;int shortest(int,int);clrscr();printf("\nEnter the no. of routers:");scanf("%d",&n);printf("\nEnter the connection matrix of routers:\n");for(i=1;i<=n;i++)for(j=1;j<=n;j++)scanf("%d",&connection[i][j].wt);for(i=1;i<=n;i++)

for(j=1;j<=n;j++)if(connection[i][j].wt!=INFIN)printf("\npath found between %d and %d with cost : %d",i,j,connection[i][j]);printf("\nEnter the source router:");scanf("%d",&source);printf("\nEnter the destination router :");scanf("%d",&dest);printf("\nSHORTEST PATH : %d",shortest(source,dest));printf("\nPress any key");getch();}int shortest(int source,int dest){int small,perm[10],current,new1,start,temp,i,dist[10],k=1;for(i=1;i<=n;i++){perm[i]=0;dist[i]=INFIN;erm[source]=1;dist[source]=0;current=source;//printf("%d",current);while(current!=dest){small=INFINITY;start=dist[current];

37

Page 38: CS2307 - Network Lab Manual(2)

for(i=1;i<=n;i++){if(perm[i]==0){new1=start+connection[current][i].wt;if(new1<dist[i])dist[i]=new1;if(dist[i]<small){small=dist[i];temp=i;}}}current=temp;perm[current]=1;}return(small);

}

OUTPUT

Enter the no. of routers: 2

Enter the connection matrix of routers:1015712

path found between 1 and 1 with cost : 10path found between 1 and 2 with cost : 15path found between 2 and 1 with cost : 7path found between 2 and 2 with cost : 12Enter the source router: 2

Enter the destination router: 1

SHORTEST PATH: 7Press any key

38

Page 39: CS2307 - Network Lab Manual(2)

RESULT

Thus the program to find the shortest path using OSPF routing protocol was executed and output was verified.

EX.NO:-7b DISTANCE VECTOR ROUTING PROTOCOL

PROGRAM

#include<stdio.h>main(){int a[50],hc[20],d[20],n,i,h[50],m,d1[50],flag,j,k,flag1,ch;char r[10][20],nn,ht;printf("Enter the number in routing table");scanf("%d",&n);j=0;for(i=0;i<n;i++){printf("Enter the Destination:Net");scanf("%d",&d[i]);printf("Enter the Hop Count:");scanf("%d",&hc[i]);printf("Enter the Next Router:");scanf("%s",&r[j][i]);}do{printf("Old routing Table");printf("\ndestination\thopcount\trouter\n");

39

Page 40: CS2307 - Network Lab Manual(2)

for(i=0;i<n;i++){printf("\nNet%d\t\t%d\t\t%c",d[i],hc[i],r[0][i]);}ht=r[0][0];

printf("\nEnter the Router Name");scanf("%s",&nn);r[0][0]=ht;

printf("\nEnter the number in message table\n");scanf("%d",&m);for(i=0;i<m;i++){printf("Enter the Destination:Net");scanf("%d",&d1[i]);printf("Enter the HopCount:");scanf("%d",&h[i]);}

printf("Message from %c",nn);for(i=0;i<m;i++){printf("\nNet%d\t%d",d1[i],h[i]);}for(i=0;i<m;i++){h[i]=h[i]+1;}printf("\nMessage from %c after increment",nn);for(i=0;i<m;i++){printf("\n%d\t%d",d1[i],h[i]);}flag=0;for(i=0;i<n;i++){for(j=0;j<m;j++){if(d[i]==d1[j]){flag=1;k=j;}}if(flag==1)

40

Page 41: CS2307 - Network Lab Manual(2)

{ if(r[0][i]==nn) { hc[i]=h[k]; r[0][i]=nn; } else { if(hc[i]>h[i]) { hc[i]=h[i]; r[0][i]=nn; } else { hc[i]=hc[i];

} } }

else{hc[i]=hc[i];}}flag1=0;for(i=0;i<m;i++){flag1=0;for(j=0;j<n;j++){if(d1[i]==d[j]){flag1=1;break;}}if(flag1!=1){d[n]=d1[i];hc[n]=h[i];r[0][n]=nn;n=n+1;}}

41

Page 42: CS2307 - Network Lab Manual(2)

printf("\nNew routing Table\n");printf("destination\thopcount\trouter\n");for(i=0;i<n;i++){printf("\nNet%d\t\t%d\t\t%c",d[i],hc[i],r[0][i]);}printf("\nDo u want to send message from another router");scanf("%d",&ch);}while(ch!=0);}

OUTPUT

Enter the number in routing table3

Enter the Destination:Net10

Enter the Hop Count:1

Enter the Next Router:a

Enter the Destination:Net11

Enter the Hop Count:2

Enter the Next Router:b

Enter the Destination:Net12

Enter the Hop Count:3

Enter the Next Router:c

Old routing Table

destination hopcount router

42

Page 43: CS2307 - Network Lab Manual(2)

Net10 1 aNet11 2 bNet12 3 c

Enter the Router Name a

Enter the number in message table

2

Enter the Destination:Net11

Enter the HopCount:3

Enter the Destination:Net12

Enter the HopCount:3

Message from a

Net11 3

Net12 3

Message from a after increment

11 4

12 4

New routing Table

destination hopcount router

et10 1 aNet11 2Net12 0 a

43

Page 44: CS2307 - Network Lab Manual(2)

Do u want to send message from another router0

RESULT

Thus the program to find the shortest path using DSDV routing protocol was executed and output was verified.

EX.NO:- 8 PERFORMANCE COMPARISION OF MAC PROTOCOLS

AIM: To compare the performance of MAC protocols

ALGORTHIM:-

Step1: create a new simulatorStep2: open the network animator file which is the namfile outmanStep3:set the agent trace and the router trace in the ON state and then get the MAC trace as OFF state.Step4: Construct four nodes namely n0,n1,n2 and n3 and the color for trandfering the packets is set as green and red.Step5:The delay time for each nodes and the node agent for each nodes are set.Step6:The droptail queues are used to transfer the packets by capturing them in a queue as specified.

PROGRAM :-

44

Page 45: CS2307 - Network Lab Manual(2)

Set ns[new Simulator]$ns color1 Blue$ns color 2 RedSet nf[open out.nam w]$ns namtrace-all $nfProc finish{}{global ns nf$ns flush_traceclose $nfexec nam out.nam & exit 0}Set no[$ns node]Set n1[$ns node]Set n2[$ns node]Set n3[$ns node]$ns duplex-link $n0 $n2 2 Mb 10ms DropTail$ns duplex-link $n1 $n2 2 Mb 10ms DropTail

$ns duplex-link $n2 $n3 1.7 Mb 20ms DropTail$ns queue-link $n0 $n2 $n3 10$ns duplex-link-op $n0 $n2 orient right-down$ns duplex-link-op $n1 $n2 orient right-up$ns duplex-link-op $n2 $n3 orient right$ns duplex-link-op $n2 $n3 queuePOs 0.5Set tcp[new Agent/TCP]$tcp set class_2$ns attach-agent $no $tcpSet sink[new Agent/TCPSink]$ns attach-agent $n3 $sink$ns connect $tcp $sink$tcp set fid_1Set ftp[new Application/FTP]$ftp attach-agent $tcp$ftp set type_FTPSet udp[new Agent/UDP]$ns attach-agent $n1 $udpSet null[new Agent/Null]$ns attach-agent $n3 $null$ns connect $udp $null$udp set fid_2Set cbr [new Application/Traffic/CBR]$cbr attach_agent $uDP$cbr set type_CBR

45

Page 46: CS2307 - Network Lab Manual(2)

$cbr set packet_size_1000$cbr set rate_1mb$cbr set random_false$ns at 0.1 “$cbr start”$ns at 1.0 “$ftp start”$ns at 4.0 “$ftp stopt”$ns at 4.5 “$cbr stop”$ns at 4.5 “$ns detach-agent $n0 $tcp;$nsdetach-agent $n3 $sink”$ns at 5.0 “finish”Puts “CBR packet size=[$cbr set packet_size_]”Puts “CBR interval=[$cbr set interval_]”$ns run

RESULT :

Thus the program for comparision of MAC protocols using NS-2 simulators has been executed successfully.

EX.NO:- 9 PERFORMANCE COMPARISION OF ROUTING PROTOCOLS

AIM: To compare the performance of Routing protocols

PROGRAM:-

AODV

Set val(mn) 10 ; # number of mobilenodesSer val(rp) AODV ;#routing protocolSet Val(x) 800Set Val(y) 800

Set as[New Simulator]#ns-random 0

Set f[open aodv10,tr,w]$ns trace-all sfSet namtrace[open aodv10,nam w]$ns namtrace-all-wireless $namtrace $val(x) $val(y)Set f0 [open packets_received.tr w]

46

Page 47: CS2307 - Network Lab Manual(2)

Set f1 [open packets_lost.tr w]Set f2 [open proj_out2. tr w]Set f3 [open proj_out3.tr w]

Set topo [new Topography]$topo load_flatgrid 800 800

create-god $val(nn)Set chan_1 [new $val(chan)]Set chan_2 [new $val(chan)]Set chan_3 [new $val(chan)]Set chan_4 [new $val(chan)]Set chan_5 [new $val(chan)]Set chan_6 [new $val(chan)]

# CONFIGURE AND CREATE NODES

DSR

Set val(nn) 10Set val(rp) DSRSet val(x) 800Set val(x) 800#set val(stop) 10.0

set ns[new Simulator]#ns-random 0Set f[open dsr15.tr,w]$ns trace-all sfSet namtrace[open dsr15.tr w]$ns namtrace-all-wireless $namtrace $val(x) $val(y)Set f0 [open packets_received.tr w]Set f1 [open packets_lost.tr w]Set f2 [open proj_out2. tr w]Set f3 [open proj_out3.tr w]

Set topo [new Topography]$topo load_flatgrid 800 800

create-god $val(nn)

Set chan_1 [new $val(chan)]Set chan_2 [new $val(chan)]

47

Page 48: CS2307 - Network Lab Manual(2)

Set chan_3 [new $val(chan)]Set chan_4 [new $val(chan)]Set chan_5 [new $val(chan)]Set chan_6 [new $val(chan)]Set chan_7 [new $val(chan)]Set chan_8 [new $val(chan)]Set chan_9 [new $val(chan)]Set chan_10 [new $val(chan)]

#CONFIGURE AND CREATE NODES

AODV NAM – Network Simulator

DSR NAM – Network Simulator

48

Page 49: CS2307 - Network Lab Manual(2)

X Graph 0f 10 seconds simulation time of AODV

X Graph 0f 10 seconds simulation time of DSR

49

Page 50: CS2307 - Network Lab Manual(2)

RESULT :-

Thus the comparing the performance of AODV and DSR is executes successfully.

EX.NO:- 10 STUDY OF UDP PERFORMANCE

Aim: To study about UDP Performance

The User Datagram Protocol (UDP) is one of the core members of the Internet

Protocol Suite, the set of network protocols used for the Internet. With UDP, computer

applications can send messages, in this case referred to as datagrams, to other hosts on

an Internet Protocol (IP) network without requiring prior communications to set up

special transmission channels or data paths. The protocol was designed by David P. Reed

in 1980 and formally defined in RFC 768.

UDP uses a simple transmission model without implicit hand-shaking dialogues

for providing reliability, ordering, or data integrity. Thus, UDP provides an unreliable

service and datagrams may arrive out of order, appear duplicated, or go missing without

notice. UDP assumes that error checking and correction is either not necessary or

performed in the application, avoiding the overhead of such processing at the network

interface level. Time-sensitive applications often use UDP because dropping packets is

50

Page 51: CS2307 - Network Lab Manual(2)

preferable to waiting for delayed packets, which may not be an option in a real-time

system. If error correction facilities are needed at the network interface level, an

application may use the Transmission Control Protocol (TCP) or Stream Control

Transmission Protocol (SCTP) which are designed for this purpose.

UDP's stateless nature is also useful for servers answering small queries from huge

numbers of clients. Unlike TCP, UDP is compatible with packet broadcast (sending to all

on local network) and multicasting (send to all subscribers).

Common network applications that use UDP include: the Domain Name System (DNS),

streaming media applications such as IPTV, Voice over IP (VoIP), Trivial File Transfer

Protocol (TFTP) and many online games.

Service ports

Main article: TCP and UDP port

UDP applications use datagram sockets to establish host-to-host communications. An

application binds a socket to its endpoint of data transmission, which is a combination of

an IP address and a service port. A port is a software structure that is identified by the

port number, a 16 bit integer value, allowing for port numbers between 0 and 65535. Port

0 is reserved, but is a permissible source port value if the sending process does not

expect messages in response.

The Internet Assigned Numbers Authority has divided port numbers into three ranges.

Port numbers 0 through 1023 are used for common, well-known services. On Unix-like

operating systems, using one of these ports requires superuser operating permission. Port

numbers 1024 through 49151 are the registered ports used for IANA-registered services.

Ports 49152 through 65535 are dynamic ports that are not officially for any specific

service, and can be used for any purpose. They are also used as ephemeral ports, from

51

Page 52: CS2307 - Network Lab Manual(2)

which software running on the host may randomly choose a port in order to define itself.

In effect, they are used as temporary ports primarily by clients when communicating

with servers.

Packet structure

UDP is a minimal message-oriented Transport Layer protocol that is documented in

IETF RFC 768.

UDP provides no guarantees to the upper layer protocol for message delivery and the

UDP protocol layer retains no state of UDP messages once sent. For this reason, UDP is

sometimes referred to as Unreliable Datagram Protocol.[citation needed]

UDP provides application multiplexing (via port numbers) and integrity

verification (via checksum) of the header and payload.[3] If transmission reliability

is desired, it must be implemented in the user's application.

bits 0 – 15 16 – 31

0 Source Port Number Destination Port Number

32 Length Checksum

64

 

Data

 

The UDP header consists of 4 fields, all of which are 2 bytes (16 bits). The use of two of

those is optional in IPv4 (pink background in table). In IPv6 only the source port is

optional (see below).

52

Page 53: CS2307 - Network Lab Manual(2)

Source port number 

This field identifies the sender's port when meaningful and should be assumed to

be the port to reply to if needed. If not used, then it should be zero. If the source

host is the client, the port number is likely to be an ephemeral port number. If the

source host is the server, the port number is likely to be a well-known port

number.

Destination port number 

This field identifies the receiver's port and is required. Similar to source port

number, if the client is the destination host then the port number will likely be an

ephemeral port number and if the destination host is the server then the port

number will likely be a well-known port number.

Length 

A field that specifies the length in bytes of the entire datagram: header and data.

The minimum length is 8 bytes since that's the length of the header. The field size

sets a theoretical limit of 65,535 bytes (8 byte header + 65,527 bytes of data) for

a UDP datagram. The practical limit for the data length which is imposed by the

underlying IPv4 protocol is 65,507 bytes (65,535 − 8 byte UDP header − 20 byte

IP header).

Checksum 

The checksum field is used for error-checking of the header and data. If no

checksum is generated by the transmitter, the field uses the value all-zeros. This

field is not optional for IPv6.

Checksum computation

The method used to compute the checksum is defined in RFC 768:

53

Page 54: CS2307 - Network Lab Manual(2)

Checksum is the 16-bit one's complement of the one's complement sum of a

pseudo header of information from the IP header, the UDP header, and the data,

padded with zero octets at the end (if necessary) to make a multiple of two octets.

In other words, all 16-bit words are summed using one's complement arithmetic.

The sum is then one's complemented to yield the value of the UDP checksum

field.

If the checksum calculation results in the value zero (all 16 bits 0) it should be

sent as the one's complement (all 1's).

The difference between IPv4 and IPv6 is in the data used to compute the

checksum.

IPv4 PSEUDO-HEADER

When UDP runs over IPv4, the checksum is computed using a PSEUDO-HEADER that contains

some of the same information from the real IPv4 header. The PSEUDO-HEADER is not the real

IPv4 header used to send an IP packet. The following table defines the PSEUDO-HEADER used

only for the checksum calculation.

bits 0 – 7 8 – 15 16 – 23 24 – 31

0 Source address

32 Destination address

64 Zeros Protocol UDP length

96 Source Port Destination Port

54

Page 55: CS2307 - Network Lab Manual(2)

128 Length Checksum

160

 

Data

 

When computing the checksum, again a PSEUDO-HEADER is used that mimics the real

IPv6 header:

The source address is the one in the IPv6 header. The destination address is the final

destination; if the IPv6 packet doesn't contain a Routing header, that will be the

destination address in the IPv6 header; otherwise, at the originating node, it will be the

address in the last element of the Routing header, and, at the receiving node, it will be

the destination address in the IPv6 header. The value of the Next Header field is the

protocol value for UDP: 17. The UDP length field is the length of the UDP header and

data.

Reliability and congestion control solutions

Lacking reliability, UDP applications must generally be willing to accept some loss,

errors or duplication. Some applications such as TFTP may add rudimentary reliability

mechanisms into the application layer as needed. Most often, UDP applications do not

require reliability mechanisms and may even be hindered by them. Streaming media,

real-time multiplayer games and voice over IP (VoIP) are examples of applications that

often use UDP. If an application requires a high degree of reliability, a protocol such as

the Transmission Control Protocol or erasure codes may be used instead.

Lacking any congestion avoidance and control mechanisms, network-based mechanisms

are required to minimize potential congestion collapse effects of uncontrolled, high rate

UDP traffic loads. In other words, since UDP senders cannot detect congestion, network-

based elements such as routers using packet queuing and dropping techniques will often

55

Page 56: CS2307 - Network Lab Manual(2)

be the only tool available to slow down excessive UDP traffic. The Datagram

Congestion Control Protocol (DCCP) is being designed as a partial solution to this

potential problem by adding end host TCP-friendly congestion control behavior to high-

rate UDP streams such as streaming media.

Comparison of UDP and TCP

Main article: Transport Layer

Transmission Control Protocol is a connection-oriented protocol, which means that it

requires handshaking to set up end-to-end communications. Once a connection is set up

user data may be sent bi-directionally over the connection.

Reliable – TCP manages message acknowledgment, retransmission and timeout.

Multiple attempts to deliver the message are made. If it gets lost along the way,

the server will re-request the lost part. In TCP, there's either no missing data, or,

in case of multiple timeouts, the connection is dropped.

Ordered – if two messages are sent over a connection in sequence, the first

message will reach the receiving application first. When data segments arrive in

the wrong order, TCP buffers the out-of-order data until all data can be properly

re-ordered and delivered to the application.

Heavyweight – TCP requires three packets to set up a socket connection, before

any user data can be sent. TCP handles reliability and congestion control.

Streaming – Data is read as a byte stream, no distinguishing indications are

transmitted to signal message (segment) boundaries.

UDP is a simpler message-based connectionless protocol. Connectionless protocols do not

set up a dedicated end-to-end connection. Communication is achieved by transmitting

56

Page 57: CS2307 - Network Lab Manual(2)

information in one direction from source to destination without verifying the readiness or

state of the receiver.

Unreliable – When a message is sent, it cannot be known if it will reach its

destination; it could get lost along the way. There is no concept of acknowledgment,

retransmission or timeout.

Not ordered – If two messages are sent to the same recipient, the order in which they

arrive cannot be predicted.

Lightweight – There is no ordering of messages, no tracking connections, etc. It is a

small transport layer designed on top of IP.

Datagrams – Packets are sent individually and are checked for integrity only if they

arrive. Packets have definite boundaries which are honored upon receipt, meaning a

read operation at the receiver socket will yield an entire message as it was originally

sent.

RESULT :

Thus the performance of UDP is studied Sucessfully.

EX.NO:- 11 STUDY OF TCP PERFORMANCE

Aim: To study about TCP Performance

The Transmission Control Protocol (TCP) is one of the core protocols of the Internet

Protocol Suite. TCP is one of the two original components of the suite, complementing

the Internet Protocol (IP), and therefore the entire suite is commonly referred to as

TCP/IP. TCP provides the service of exchanging data directly between two network

hosts, whereas IP handles addressing and routing message across one or more networks.

In particular, TCP provides reliable, ordered delivery of a stream of bytes from a

57

Page 58: CS2307 - Network Lab Manual(2)

program on one computer to another program on another computer. TCP is the protocol

that major Internet applications rely on, applications such as the World Wide Web, e-

mail, and file transfer. Other applications, which do not require reliable data stream

service, may use the User Datagram Protocol (UDP) which provides a datagram service

that emphasizes reduced latency over reliability

Network function

TCP provides a communication service at an intermediate level between an application

program and the Internet Protocol (IP). That is, when an application program desires to

send a large chunk of data across the Internet using IP, instead of breaking the data into

IP-sized pieces and issuing a series of IP requests, the software can issue a single request

to TCP and let TCP handle the IP details.

IP works by exchanging pieces of information called packets. A packet is a sequence of

octets and consists of a header followed by a body. The header describes the packet's

destination and, optionally, the routers to use for forwarding until it arrives at its

destination. The body contains the data IP is transmitting.

Due to network congestion, traffic load balancing, or other unpredictable network

behavior, IP packets can be lost, duplicated, or delivered out of order. TCP detects these

problems, requests retransmission of lost packets, rearranges out-of-order packets, and

even helps minimize network congestion to reduce the occurrence of the other problems.

Once the TCP receiver has finally reassembled a perfect copy of the data originally

transmitted, it passes that datagram to the application program. Thus, TCP abstracts the

application's communication from the underlying networking details.

58

Page 59: CS2307 - Network Lab Manual(2)

TCP is utilized extensively by many of the Internet's most popular applications,

including the World Wide Web (WWW), E-mail, File Transfer Protocol, Secure Shell,

peer-to-peer file sharing, and some streaming media applications.

TCP is optimized for accurate delivery rather than timely delivery, and therefore,

TCP sometimes incurs relatively long delays (in the order of seconds) while

waiting for out-of-order messages or retransmissions of lost messages. It is not

particularly suitable for real-time applications such as Voice over IP. For such

applications, protocols like the Real-time Transport Protocol (RTP) running over

the User Datagram Protocol (UDP) are usually recommended instead.

TCP is a reliable stream delivery service that guarantees delivery of a data stream sent

from one host to another without duplication or losing data. Since packet transfer is not

reliable, a technique known as positive acknowledgment with retransmission is used to

guarantee reliability of packet transfers. This fundamental technique requires the receiver

to respond with an acknowledgment message as it receives the data. The sender keeps a

record of each packet it sends, and waits for acknowledgment before sending the next

packet. The sender also keeps a timer from when the packet was sent, and retransmits a

packet if the timer expires. The timer is needed in case a packet gets lost or corrupted.

TCP consists of a set of rules: for the protocol, that are used with the Internet Protocol,

and for the IP, to send data "in a form of message units" between computers over the

Internet. At the same time that IP takes care of handling the actual delivery of the data,

TCP takes care of keeping track of the individual units of data transmission, called

segments, that a message is divided into for efficient routing through the network. For

example, when an HTML file is sent from a Web server, the TCP software layer of that

server divides the sequence of octets of the file into segments and forwards them

individually to the IP software layer (Internet Layer). The Internet Layer encapsulates

59

Page 60: CS2307 - Network Lab Manual(2)

each TCP segment into an IP packet by adding a header that includes (among other data)

the destination IP address. Even though every packet has the same destination address,

they can be routed on different paths through the network. When the client program on

the destination computer receives them, the TCP layer (Transport Layer) reassembles the

individual segments and ensures they are correctly ordered and error free as it streams

them to an application.

Protocol operation

A Simplified TCP State Diagram. See TCP EFSM diagram for a more detailed state diagram

including the states inside the ESTABLISHED state.

TCP protocol operations may be divided into three phases. Connections must be properly

established in a multi-step handshake process (connection establishment) before entering the

data transfer phase. After data transmission is completed, the connection termination closes

established virtual circuits and releases all allocated resources.

A TCP connection is managed by an operating system through a programming interface that

represents the local end-point for communications, the Internet socket. During the lifetime of

a TCP connection it undergoes a series of state changes:

1. LISTEN : In case of a server, waiting for a connection request from any remote

client.

2. SYN-SENT : waiting for the remote peer to send back a TCP segment with the SYN

and ACK flags set. (usually set by TCP clients)

60

Page 61: CS2307 - Network Lab Manual(2)

3. SYN-RECEIVED : waiting for the remote peer to send back an acknowledgment

after having sent back a connection acknowledgment to the remote peer. (usually set

by TCP servers)

4. ESTABLISHED : the port is ready to receive/send data from/to the remote peer.

5. FIN-WAIT-1

6. FIN-WAIT-2

7. CLOSE-WAIT

8. CLOSING

9. LAST-ACK

10. TIME-WAIT : represents waiting for enough time to pass to be sure the remote peer

received the acknowledgment of its connection termination request. According to

RFC 793 a connection can stay in TIME-WAIT for a maximum of four minutes.

11. CLOSEDConnection establishment

To establish a connection, TCP uses a three-way handshake. Before a client attempts to

connect with a server, the server must first bind to a port to open it up for connections: this is

called a passive open. Once the passive open is established, a client may initiate an active

open. To establish a connection, the three-way (or 3-step) handshake occurs:

1. SYN: The active open is performed by the client sending a SYN to the server. It sets

the segment's sequence number to a random value A.

2. SYN-ACK: In response, the server replies with a SYN-ACK. The acknowledgment

number is set to one more than the received sequence number (A + 1), and the

sequence number that the server chooses for the packet is another random number, B.

61

Page 62: CS2307 - Network Lab Manual(2)

3. ACK: Finally, the client sends an ACK back to the server. The sequence number is

set to the received acknowledgement value i.e. A + 1, and the acknowledgement

number is set to one more than the received sequence number i.e. B + 1.

At this point, both the client and server have received an acknowledgment of the connection.

Data transfer

There are a few key features that set TCP apart from User Datagram Protocol:

Ordered data transfer - the destination host rearranges according to sequence number

Retransmission of lost packets - any cumulative stream not acknowledged is

retransmitted

Error-free data transfer (The checksum in UDP is optional)

Flow control - limits the rate a sender transfers data to guarantee reliable delivery.

The receiver continually hints the sender on how much data can be received

(controlled by the sliding window). When the receiving host's buffer fills, the next

acknowledgment contains a 0 in the window size, to stop transfer and allow the data

in the buffer to be processed.

Congestion control

Reliable transmission

TCP uses a sequence number to identify each byte of data. The sequence number identifies

the order of the bytes sent from each computer so that the data can be reconstructed in order,

regardless of any fragmentation, disordering, or packet loss that may occur during

transmission. For every payload byte transmitted the sequence number must be incremented.

In the first two steps of the 3-way handshake, both computers exchange an initial sequence

number (ISN). This number can be arbitrary, and should in fact be unpredictable to defend

against TCP Sequence Prediction Attacks.

62

Page 63: CS2307 - Network Lab Manual(2)

TCP primarily uses a cumulative acknowledgment scheme, where the receiver sends an

acknowledgment signifying that the receiver has received all data preceding the

acknowledged sequence number. Essentially, the first byte in a segment's data field is

assigned a sequence number, which is inserted in the sequence number field, and the

receiver sends an acknowledgment specifying the sequence number of the next byte they

expect to receive. In addition to cumulative acknowledgments, TCP receivers can also send

selective acknowledgments to provide further information (see selective acknowledgments).

Maximum segment size

The Maximum segment size (MSS) is the largest amount of data, specified in bytes, that

TCP is willing to send in a single segment. For best performance, the MSS should be set

small enough to avoid IP fragmentation, which can lead to excessive retransmissions if there

is packet loss. To try to accomplish this, typically the MSS is negotiated using the MSS

option when the TCP connection is established, in which case it is determined by the

maximum transmission unit (MTU) size of the data link layer of the networks to which the

sender and receiver are directly attached. Furthermore, TCP senders can use Path MTU

discovery to infer the minimum MTU along the network path between the sender and

receiver, and use this to dynamically adjust the MSS to avoid IP fragmentation within the

network.

TCP Timestamps

TCP timestamps, defined in RFC 1323, help TCP compute the round-trip time between the

sender and receiver. Timestamp options include a 4-byte timestamp value, where the sender

inserts its current value of its timestamp clock, and a 4-byte echo reply timestamp value,

where the receiver generally inserts the most recent timestamp value that it has received. The

sender uses the echo reply timestamp in an acknowledgment to compute the total elapsed

time since the acknowledged segment was sent.

63

Page 64: CS2307 - Network Lab Manual(2)

TCP timestamps are also used to help in the case where TCP sequence numbers encounter

their 232 bound and "wrap around" the sequence number space. This scheme is known as

Protect Against Wrapped Sequence numbers, or PAWS (see RFC 1323 for details).

Furthermore, the Eifel detection algorithm, defined in RFC 3522, which detects unnecessary

loss recovery

Connection termination

The connection termination phase uses, at most, a four-way handshake, with each side of the

connection terminating independently. When an endpoint wishes to stop its half of the

connection, it transmits a FIN packet, which the other end acknowledges with an ACK.

Therefore, a typical tear-down requires a pair of FIN and ACK segments from each TCP

endpoint.

A connection can be "half-open", in which case one side has terminated its end, but the other

has not. The side that has terminated can no longer send any data into the connection, but the

other side can. The terminating side should continue reading the data until the other side

terminates as well.

It is also possible to terminate the connection by a 3-way handshake, when host A sends a

FIN and host B replies with a FIN & ACK (merely combines 2 steps into one) and host A

replies with an ACK. This is perhaps the most common method.

It is possible for both hosts to send FINs simultaneously then both just have to ACK. This

could possibly be considered a 2-way handshake since the FIN/ACK sequence is done in

parallel for both directions.

Some host TCP stacks may implement a "half-duplex" close sequence, as Linux or HP-

UX do. If such a host actively closes a connection but still has not read all the incoming

data the stack already received from the link, this host sends a RST instead of a FIN

(Section 4.2.2.13 in RFC 1122). This allows a TCP application to be sure the remote

application has read all the data the former sent—waiting the FIN from the remote side,

when it actively closes the connection. However, the remote TCP stack cannot

64

Page 65: CS2307 - Network Lab Manual(2)

distinguish between a Connection Aborting RST and this Data Loss RST. Both cause the

remote stack to throw away all the data it received, but that the application still didn't

read.[clarification needed]

Some application protocols may violate the OSI model layers, using the TCP open/close

handshaking for the application protocol open/close handshaking - these may find the RST

problem on active close. As an example:

s = connect(remote);

send(s, data);

close(s);

For a usual program flow like above, a TCP/IP stack like that described above does not

guarantee that all the data arrives to the other application unless the programmer is sure that

the remote side will not send anything.

TCP ports

Main article: TCP and UDP port

TCP uses the notion of port numbers to identify sending and receiving application end-

points on a host, or Internet sockets. Each side of a TCP connection has an associated 16-bit

unsigned port number (0-65535) reserved by the sending or receiving application. Arriving

TCP data packets are identified as belonging to a specific TCP connection by its sockets,

that is, the combination of source host address, source port, destination host address, and

destination port. This means that a server computer can provide several clients with several

services simultaneously, as long as a client takes care of initiating any simultaneous

connections to one destination port from different source ports.

65

Page 66: CS2307 - Network Lab Manual(2)

Port numbers are categorized into three basic categories: well-known, registered, and

dynamic/private. The well-known ports are assigned by the Internet Assigned Numbers

Authority (IANA) and are typically used by system-level or root processes. Well-known

applications running as servers and passively listening for connections typically use these

ports. Some examples include: FTP (21), SSH (22), TELNET (23), SMTP (25) and HTTP

(80). Registered ports are typically used by end user applications as ephemeral source ports

when contacting servers, but they can also identify named services that have been registered

by a third

RESULT :-

Thus the performance of TCP is studied successfully.

66