network lab by armstrong

66
SRI RAM ENGINERRING COLLEGE PERUMALPATTU Prepared by Asst.Prof J.Armstrong Joseph Network Lab TCP - CHAT PROGRAM Ex.1 AIM: To implement TCP client-server chat. ALGORITHM: Server: 1. Start 2. Create a socket with address family AF_INET, type SOCK_STREAM and default protocol. 3. Initialize the socket and set its attributes. Assign any port number as desired. 4. Bind the server to the socket using bind() function. 5. Establish the listen queue using the listen() function. 6. Wait for the client request. On request, establish a connection using accept() function. 7. Repeat steps 8-10 until the server sends "bye" 8. Read the message from the client using read() function. Display the message. 9. If the client message is "bye", go to step 11 10.Accept the server message and write it to the client using write() function. 11.Close the connection. 12.Go to step 6. Client: 1. Start 2. Create a socket with address family AF_INET, type SOCK_STREAM and default protocol. 3. Initialize the socket and set its attributes. Set the required port number. 4. Connect to the server using connect() function to initiate the request. 5. Repeat steps 6-8 until the server sends "bye" 6. Accept the client message and write it to the server using write() function. 7. If the client message is "bye", go to step 9 8. Read the message from the server using read() function. Display the message. 1

Upload: armstrongjoseph1908

Post on 08-Apr-2015

402 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Network Lab by Armstrong

SRI RAM ENGINERRING COLLEGEPERUMALPATTU

Prepared by Asst.Prof J.Armstrong JosephNetwork Lab

TCP - CHAT PROGRAMEx.1

AIM: To implement TCP client-server chat.

ALGORITHM:

Server:1. Start2. Create a socket with address family AF_INET, type SOCK_STREAM and default protocol.3. Initialize the socket and set its attributes. Assign any port number as desired.4. Bind the server to the socket using bind() function.5. Establish the listen queue using the listen() function.6. Wait for the client request. On request, establish a connection using accept() function. 7. Repeat steps 8-10 until the server sends "bye"8. Read the message from the client using read() function. Display the message.9. If the client message is "bye", go to step 1110.Accept the server message and write it to the client using write() function.11.Close the connection.12.Go to step 6.

Client:1. Start2. Create a socket with address family AF_INET, type SOCK_STREAM and default protocol.3. Initialize the socket and set its attributes. Set the required port number.4. Connect to the server using connect() function to initiate the request.5. Repeat steps 6-8 until the server sends "bye"6. Accept the client message and write it to the server using write() function.7. If the client message is "bye", go to step 98. Read the message from the server using read() function. Display the message.

CODE:

Server:

#include<stdio.h>#include<sys/socket.h>#include<iostream.h>

1

Page 2: Network Lab by Armstrong

#include<netinet/in.h>#include<stdlib.h>#include<unistd.h>#include<string.h>#include<netdb.h>#include<arpa/inet.h>#include<sys/types.h>#include<time.h># define MAX 100int cwork(int);int main(){int socketmain,socketclient,child,port=4567;struct sockaddr_in serv;char str[100];if((socketmain = socket(AF_INET,SOCK_STREAM,0))<0){cout <<" server cannot open the main socket ";exit(0);}bzero(&serv,sizeof(serv));serv.sin_family = AF_INET;serv.sin_addr.s_addr = htonl(INADDR_ANY);serv.sin_port=htons(port);if(bind(socketmain,(struct sockaddr *) &serv,sizeof(serv)) < 0 ){cout << " server bin fail";exit(0);}listen(socketmain,15);for(;;){if((socketclient = accept(socketmain,0,0)) < 0 ){cout << "client is bad ";exit(0);}if((child=fork()) < 0){cout << "failed to create child";exit(1);}else if( child ==0){close(socketmain);cwork(socketclient);

2

Page 3: Network Lab by Armstrong

close(socketclient);exit(0);}close(socketclient);}}int cwork(int socketclient){char buf[81];int msglen;bzero(buf,81);cout << " socket used " << socketclient;for(;;){if((msglen = recv(socketclient,buf,81,0)) < 0){cout << " error during the child reception";exit(1);}if(msglen == 81){ buf[msglen] = '\0';cout << " \n message " << buf;}if(strcmp(buf,"bye") == 0){strcpy(buf,"bye");send(socketclient,buf,strlen(buf),0);break;}else{cout << " \nenter the message for the client";cin >> buf;send(socketclient,buf,strlen(buf),0);msglen=0;

}

}

}

Client:

3

Page 4: Network Lab by Armstrong

#include<stdio.h>#include<sys/socket.h>#include<iostream.h>#include<netinet/in.h>#include<stdlib.h>#include<unistd.h>#include<string.h>#include<netdb.h>#include<arpa/inet.h>#include<sys/types.h>#include<errno.h>#include<time.h># define MAX 100# define len 81int cwork(int);int main(int argc,char **argv){int sockfd,n;struct sockaddr_in serv;char str[100];if(argc != 3){cout << " erroe message ";exit(0);}if((sockfd = socket(AF_INET,SOCK_STREAM,0))<0){cout <<" socket not created ";exit(0); }bzero(&serv,sizeof(serv));serv.sin_family = AF_INET;serv.sin_port=htons(atoi(argv[2]));if(inet_pton(AF_INET,argv[1],&serv.sin_addr) <= 0) { cout << " conversion error " ; exit(0); } if(connect(sockfd,(struct sockaddr *) &serv,sizeof(serv)) < 0 ) { cout << " connect fail"; exit(0); } cout << " connected "; for(;;)

4

Page 5: Network Lab by Armstrong

{ while(strcmp(str,"bye")!=0) { cout << "\n enter the message to sever ";cin>>str; write(sockfd,str,sizeof(str)); n=read(sockfd,str,100); str[n] = '\0'; cout << " from server " << str << endl; } break;

}

}

OUTPUT:

In server terminal[armstrong@cseserver~]$c++ tcpser.cpp –o tcpser

[armstrong@cseserver~]$../tcpserSocket used 4message heyEnter the message for client: himessage byeEnter the message for client:bye

In Client terminal[armstrong@cseserver~]$c++ tcpcli.cpp –o tcpcli

[armstrong@cseserver~]$./tcpcli 192.168.6.151 4567Enter the message for server: heymessage hiEnter the message for server:byemessage bye

Result:Thus the program was executed successfully.

5

Page 6: Network Lab by Armstrong

TCP - DATE AND TIME

Ex.2

AIM:To display date and time of server from client using TCP.

ALGORITHM:Server:

1. Start2. Create a socket with address family AF_INET, type SOCK_STREAM

and default protocol.3. Initialize the socket and set its attributes. Assign a specific

port number as desired.4. Bind the server to the socket using bind() function.5. Wait for the client request. On request, establish a connection

using accept() function. 6. Fork a child process. Perform steps 7-10 for each process.7. read the message (indicates ‘ctime’) from the client through the

connection.8. Display the client’s message.9. Send an acknowledgement message(‘time’ and ‘date’) to the client.10.Exit the child process.11.Close the connection and go to step 5.

Client:1. Start2. Create a socket with address family AF_INET, type SOCK_STREAM and

default protocol.3. Initialize the socket and set its attributes. Set the required

port number.4. Connect to the server using connect() function to initiate the

request.5. Send the message (request of ‘time’ and ‘date’) to the server.6. Receive the acknowledgement from the server7. Stop

Code:-

Server:-

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

6

Page 7: Network Lab by Armstrong

#include<time.h># define MAX 100# define len 81int cwork(int);int main(){int socketmain,socketclient,child,port=2000;struct sockaddr_in serv;char str[100];if((socketmain = socket(AF_INET,SOCK_STREAM,0))<0){cout <<" server cannot open the main socket ";exit(0);}bzero(&serv,sizeof(serv));serv.sin_family = AF_INET;serv.sin_addr.s_addr = htonl(INADDR_ANY);serv.sin_port=htons(port);if(bind(socketmain,(struct sockaddr *) &serv,sizeof(serv)) < 0 ){cout << " server bind fail";exit(0);}listen(socketmain,15);for(;;){if((socketclient = accept(socketmain,0,0)) < 0 ){cout << "client is bad ";exit(0);}if((child=fork()) < 0){cout << "failed to create child";exit(1);}

else if( child ==0){close(socketmain);cwork(socketclient);close(socketclient);exit(0);}close(socketclient);}

7

Page 8: Network Lab by Armstrong

}

Client:-

#include<stdio.h>#include<sys/socket.h>#include<iostream.h>#include<netinet/in.h>#include<stdlib.h>#include<unistd.h>#include<string.h>#include<netdb.h>#include<arpa/inet.h>#include<sys/types.h>#include<errno.h>#include<time.h># define MAX 100

int cwork(int);

int main(int argc,char **argv){int sockfd,n;struct sockaddr_in serv;char str[100];if(argc != 3){cout << "Error... in command line argument... ";exit(0);}if((sockfd = socket(AF_INET,SOCK_STREAM,0))<0){cout <<"Socket could not be created...";exit(0);}bzero(&serv,sizeof(serv));serv.sin_family = AF_INET;serv.sin_port=htons(atoi(argv[2]));if(inet_pton(AF_INET,argv[1],&serv.sin_addr) <= 0)

8

Page 9: Network Lab by Armstrong

{cout <<"Conversion error " ;exit(0);}if(connect(sockfd,(struct sockaddr *) &serv,sizeof(serv)) < 0 ){cout <<"Connect fail";exit(0);}cout << " connected ";cout << " enter the message to server ";gets(str);write(sockfd,str,sizeof(str));n=read(sockfd,str,100);str[n] = '\0';cout << " from server " << str << endl;}

OUTPUT:

In server terminal[armstrong@cseserver~]$c++ dateserv.cpp –o dateserv

[armstrong@cseserver~]$../ dateserv

Socket used 4message abcd

In Client terminal[armstrong@cseserver~]$c++ dateclient.cpp –o dateclient

[armstrong@cseserver~]$./dateclient 192.168.6.151 2000Connectedenter the message to server : abcdFron server Tue Jul 06 11:41:12 2010

Result:Thus the program was executed successfully.

9

Page 10: Network Lab by Armstrong

DOMAIN NAME SERVER using TCPEx.3

AIM: To implement Domain name server using TCP client server program.

ALGORITHM

Server:1. Create a socket on server side using socket routine.2. Assign IP address ,port number and the protocol family to the members of struct sockaddr_in3. Bind IP address, port number and protocol family to the socket.4. Listen for request from the client.5 Accept connection from the client application6. Obtain the Hostname and retrieve address using gethostbyname function.7. Write the host address to the client side.8. Close socket.

Client:1. Create socket on client side using socket routine.2. Assign IP address, Port number and Protocol family.3. Connect to the server using connect routine.4. Enter the hostname and write to the server.5. Read the IP address and display it.6. Close the socket.

Code:-

server:

#include<iostream.h>#include<stdio.h>#include<stdlib.h>#include<string.h>#include<unistd.h>#include<netdb.h>#include<sys/socket.h>#include<sys/types.h>#include<arpa/inet.h>#include<netinet/in.h>#define SER_PORT 6022int main(){ int a, sersock, newsock; char str2[100], host[25]; void *buf, *buf2; struct sockaddr_in seraddr; struct sockaddr_in clinfo;

10

Page 11: Network Lab by Armstrong

struct hostent *hp; socklen_t size=sizeof(clinfo);seraddr.sin_family=AF_INET;seraddr.sin_port=htons(SER_PORT);seraddr.sin_addr.s_addr=htonl(INADDR_ANY);if((sersock=socket(AF_INET, SOCK_STREAM,0))<0){ cout<<"\n Socket"; exit(0);}if(bind(sersock,(struct sockaddr *) &seraddr,sizeof(seraddr)) <0 ){ cout<<"\n Bind"; exit(0);}if(listen(sersock,1)<0){ cout<<"\nListen"; exit(0);}if((newsock=accept(sersock,(struct sockaddr *)&clinfo,&size))<0){ cout<<"\n Accept"; exit(0);}else cout<<"\n Connected to :" << inet_ntoa(clinfo.sin_addr);read(newsock,host,sizeof(host)); cout<<host;hp=gethostbyname(host);inet_ntop(AF_INET,hp->h_addr,str2,sizeof(str2)); cout<< str2;write(newsock,str2,strlen(str2)+1);close(newsock);

close(sersock);return 0;}

CLIENT:

#include<iostream.h>

11

Page 12: Network Lab by Armstrong

#include<stdio.h>#include<unistd.h>#include<sys/socket.h>#include<sys/types.h>#include<arpa/inet.h>#include<netinet/in.h>#define SER_PORT 6022int main(int count, char *arg[]){ int a, clisock, x; char str2[25], host[25]; struct sockaddr_in cliaddr;cliaddr.sin_family=AF_INET;cliaddr.sin_port=htons(SER_PORT);cliaddr.sin_addr.s_addr=inet_addr(arg[1]);clisock=socket(AF_INET, SOCK_STREAM,0);if(clisock<0){ cout<<"\nSocket";exit(0); }if((x=connect(clisock, (struct sockaddr *)&cliaddr, sizeof(cliaddr)))<0){ cout<<"\nConnect";exit(0);} cout<<" \nEnter the domain name:"; cin>> host; write(clisock, host, strlen(host)+1); read(clisock, str2, sizeof(str2)); cout<< str2;close(clisock);return 0;}

OUTPUT:

[armstrongl@cseserver ~]$ c++ dnscli.cpp

[armstrongl@cseserver ~]$ ./a.out 0 192.168.6.151

Enter the domain name:localhost127.0.0.1[armstrong@cseserver ~]$

[armstrongl@cseserver ~]$ c++ dnsserv.cpp

12

Page 13: Network Lab by Armstrong

[armstrongl@cseserver ~]$ ./a.out

Connected to 127.0.0.1:localhost127.0.0.1[armstrongl@cseserver ~]$

Result:Thus the program was executed successfully.

13

Page 14: Network Lab by Armstrong

DOMAIN NAME SERVER using UDPEx.4

AIM: To implement Domain name server using UDP client server program.

ALGORITHM

Server:1. Create a socket on server side using socket routine.2. Assign IP address ,port number and the protocol family to the members of struct sockaddr_in3. Bind IP address, port number and protocol family to the socket.4. Listen for request from the client.5 Accept connection from the client application6. Obtain the Hostname and retrieve address using gethostbyname function.7. Write the host address to the client side.8. Close socket.

Client:1. Create socket on client side using socket routine.2. Assign IP address, Port number and Protocol family.3. Connect to the server using connect routine.4. Enter the hostname and write to the server.5. Read the IP address and display it.6. Close the socket.

Code:-

server:

#include<iostream.h>#include<stdio.h>#include<stdlib.h>#include<string.h>#include<unistd.h>#include<netdb.h>#include<sys/socket.h>#include<sys/types.h>#include<arpa/inet.h>#include<netinet/in.h>void dg_echo(int sockfd,struct sockaddr* pcliaddr,socklen_t clilen);int main(int argc,char **argv){int sockfd;char mesg2[100];struct hostent *hp;

14

Page 15: Network Lab by Armstrong

struct sockaddr_in servaddr,cliaddr;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(9877);bind(sockfd,(struct sockaddr*)&servaddr,sizeof(servaddr));dg_echo(sockfd,(struct sockaddr*)&cliaddr,sizeof(cliaddr));}void dg_echo(int sockfd,struct sockaddr* pcliaddr,socklen_t clilen){int n;socklen_t len;struct hostent *hp;char mesg[100];for(;;){len=clilen;n=recvfrom(sockfd,mesg,100,0,pcliaddr,&len);cout<<mesg;hp=gethostbyname(mesg);inet_ntop(AF_INET,hp->h_addr,mesg,sizeof(mesg));cout<<mesg;sendto(sockfd,mesg,n,0,pcliaddr,len);}}

client:

#include<iostream.h>#include<stdio.h>#include<unistd.h>#include<sys/socket.h>#include<sys/types.h>#include<arpa/inet.h>#include<netinet/in.h>void dg_cli(FILE *fp,int sockfd,struct sockaddr* pservaddr,socklen_t servlen);int main(int argc,char **argv){int sockfd;struct sockaddr_in servaddr;if(argc!=2){

15

Page 16: Network Lab by Armstrong

cout<<"\n usage: updcli ";exit(0);}bzero(&servaddr,sizeof(servaddr));servaddr.sin_family=AF_INET;servaddr.sin_port=htons(9877);inet_pton(AF_INET,argv[1],&servaddr.sin_addr);sockfd=socket(AF_INET,SOCK_DGRAM,0);cout<<"\n enter the host name:";dg_cli(stdin,sockfd,(struct sockaddr*) &servaddr,sizeof(servaddr));exit(0);}void dg_cli(FILE *fp,int sockfd,struct sockaddr* pservaddr,socklen_t servlen){int n;char sendline[100], recvline[101];while(fgets(sendline,100,fp)!=NULL){sendto(sockfd,sendline,strlen(sendline),0,pservaddr,servlen);n=recvfrom(sockfd,recvline,100,0,NULL,NULL);recvline[n]=0;fputs(recvline,stdout);}}

OUTPUT:

[armstrongl@cseserver ~]$ c++ dnscli.cpp

[armstrongl@cseserver ~]$ ./a.out 0 192.168.6.151

Enter the domain name:localhost127.0.0.1[armstrong@cseserver ~]$

[armstrongl@cseserver ~]$ c++ dnsserv.cpp

[armstrongl@cseserver ~]$ ./a.out

Connected to 127.0.0.1:localhost127.0.0.1[armstrongl@cseserver ~]$

Result:Thus the program was executed successfully.

16

Page 17: Network Lab by Armstrong

Create a RAW socket with UDP protocolEx.5

AIM: To test a RAW socket with UDP protocol

ALGORITHM

Server:1. Create a raw socket using socket routine.2. Assign IP address ,port number and the protocol family to the members of struct sockaddr_in for source and destination addresses.3. Fabricate the IP header with standard header structures but assign our own values.4. Fabricate the UDP header with source port number and destination port number.5. Calculate the checksum for integrity.6. Build our own packet structure using setsockopt(). 7. send for every 2 second for 100 count 8. Close socket.

Code:-

#include <unistd.h>#include <iostream.h>#include <stdio.h>#include <sys/socket.h>#include <netinet/ip.h>#include <netinet/udp.h> // The packet length#define PCKT_LEN 8192 // Can create separate header file (.h) for all headers' structure// The IP header's structurestruct ipheader { unsigned char      iph_ihl:5, iph_ver:4; unsigned char      iph_tos; unsigned short int iph_len; unsigned short int iph_ident; unsigned char      iph_flag; unsigned short int iph_offset; unsigned char      iph_ttl; unsigned char      iph_protocol; unsigned short int iph_chksum; unsigned int       iph_sourceip; unsigned int       iph_destip;

17

Page 18: Network Lab by Armstrong

}; // UDP header's structurestruct udpheader { unsigned short int udph_srcport; unsigned short int udph_destport; unsigned short int udph_len; unsigned short int udph_chksum;};// total udp header length: 8 bytes (=64 bits) // Function for checksum calculation. From the RFC,// the checksum algorithm is://  "The checksum field is the 16 bit one's complement of //the one's  complement sum of all 16 bit words in the //header.  For purposes of  computing the checksum, the //value of the checksum field is zero."unsigned short csum(unsigned short *buf, int nwords){       //

        unsigned long sum;        for(sum=0; nwords>0; nwords--)                sum += *buf++;        sum = (sum >> 16) + (sum &0xffff);        sum += (sum >> 16);        return (unsigned short)(~sum);}

// Source IP, source port, target IP, target port from the //command line argumentsint main(int argc, char *argv[]){int sd;// No data/payload just datagramchar buffer[PCKT_LEN];// Our own headers' structuresstruct ipheader *ip = (struct ipheader *) buffer;struct udpheader *udp = (struct udpheader *) (buffer + sizeof(struct ipheader));// Source and destination addresses: IP and portstruct sockaddr_in sin, din;int one = 1;const int *val = &one; memset(buffer, 0, PCKT_LEN); if(argc != 5){

18

Page 19: Network Lab by Armstrong

cout<<"- Invalid parameters!!!\n";cout<<"- Usage %s <source hostname/IP> <source port> <target hostname/IP> <target port>\n"<< argv[0];exit(-1);} // Create a raw socket with UDP protocolsd = socket(PF_INET, SOCK_RAW, IPPROTO_UDP);if(sd < 0){cout<<"socket() error";// If something wrong just exitexit(-1);}elsecout<<"socket() - Using SOCK_RAW socket and UDP protocol is OK.\n"; // The source is redundant, may be used later if needed// The address familysin.sin_family = AF_INET;din.sin_family = AF_INET;// Port numberssin.sin_port = htons(atoi(argv[2]));din.sin_port = htons(atoi(argv[4]));// IP addressessin.sin_addr.s_addr = inet_addr(argv[1]);din.sin_addr.s_addr = inet_addr(argv[3]); // Fabricate the IP header or we can use the// standard header structures but assign our own values.ip->iph_ihl = 5;ip->iph_ver = 4;ip->iph_tos = 16; // Low delayip->iph_len = sizeof(struct ipheader) + sizeof(struct udpheader);ip->iph_ident = htons(54321);ip->iph_ttl = 64; // hopsip->iph_protocol = 17; // UDP// Source IP address, can use spoofed address here!!!ip->iph_sourceip = inet_addr(argv[1]);// The destination IP addressip->iph_destip = inet_addr(argv[3]); // Fabricate the UDP header. Source port number, redundantudp->udph_srcport = htons(atoi(argv[2]));// Destination port numberudp->udph_destport = htons(atoi(argv[4]));

19

Page 20: Network Lab by Armstrong

udp->udph_len = htons(sizeof(struct udpheader));// Calculate the checksum for integrityip->iph_chksum = csum((unsigned short *)buffer, sizeof(struct ipheader) + sizeof(struct udpheader));// Inform the kernel do not fill up the packet structure. we will build our own...if(setsockopt(sd, IPPROTO_IP, IP_HDRINCL, val, sizeof(one)) < 0){cout<<"setsockopt() error";exit(-1);}elsecout<<"setsockopt() is OK.\n"; // Send loop, send for every 2 second for 100 countcout<<"Trying...\n";cout<<"Using raw socket and UDP protocol\n");cout<<"Using Source IP: “<< arv[1]<<” port:”<<atoi(argv[2])<<” Target IP:”<<argv[3]<<” port:”<< atoi(argv[4]) \n; int count;for(count = 1; count <=20; count++){if(sendto(sd, buffer, ip->iph_len, 0, (struct sockaddr *)&sin, sizeof(sin)) < 0)// Verify{Cout<<"sendto() error";exit(-1);}else{Cout<<"Count #%u - sendto() is OK.\n" << count);sleep(2);}}close(sd);return 0;}

 

OUTPUT:-

[root@bakawali testraw]# c++ rawudp.cpp -o rawudp[root@bakawali testraw]# ./rawudp- Invalid parameters!!!

20

Page 21: Network Lab by Armstrong

- Usage ./rawudp <source hostname/IP> <source port> <target hostname/IP> <target port>[root@bakawali testraw]# ./rawudp 192.168.2.222 21 192.168.1.10 8080socket() - Using SOCK_RAW socket and UDP protocol is OK.setsockopt() is OK.Trying...Using raw socket and UDP protocolUsing Source IP: 192.168.10.10 port: 21, Target IP: 203.106.93.91 port: 8080.Count #1 - sendto() is OK.Count #2 - sendto() is OK.Count #3 - sendto() is OK.Count #4 - sendto() is OK.Count #5 - sendto() is OK.Count #6 - sendto() is OK.Count #7 - sendto() is OK....

Result:Thus the program was executed successfully.

21

Page 22: Network Lab by Armstrong

Client server application Using RPCEx.6

AIM: To implement client server application (generating Fibonacci series) using RPC

ALGORITHM 1. Enter and compile the source codes. This application uses four

source files.

(i) The first code fie, intf.java defines the remote interface that is provided by the server. It contains the method that accepts the number to generate Fibonacci series. All remote methods can throw a RemoteException.

(ii) The second source file is, impl.java implements the remote interface, which provides functionality that is needed to make objects available from remote machines.

(iii) The third source file is rmis.java, contains main program of the server machine. Its primary function is to update the RMI registry on that machine. This is done by using the rebind() method of the Naming class. The first argument to the rebind() method is a string that names the server as “rmis”. Its second argument is a reference to an instance of “impl”.

(iv) The fourth source file is, rmic.java implements the client side of this distributed application

2. Generate Stubs and skeletons(i) A stub is a java object that resides on the client machine. Its function is

to represent the same interfaces as the remote server. Remote method calls initiated by the client are actually directed to the stub.

(ii) A skeleton is a Java object that resides on the server machine. It works with other parts of the 1.1 RMI system to receive requests, perform deserialization, and invoke the appropriate code on the server. The skeleton mechanism is not required for Java2 code.

(iii) To generate stubs and skeletons, use a tool called RMI complier, which is invoked from the command tool as

rmic implThis command generates two new lines impl_Skel.class(skeleton) and

impl_Stub.class(stub). 3. Install files on the client and server machines. (Note:- Client and server is in a

single machine, this step is not necessary)(i) Copy rmic.class, impl_Stub.class and intf.class to a directory on the

client machine. (ii) Copy rmis.class, impl.class, impl_Skel.class and intf.class to a

directory on the server machine4. Start the RMI registry on the server machine (it maps names to object reference

accessing the remote names registered on the server and a security

manager for RMI(Remote Method Invocation)start rmiregistry

5. Start the servejava rmis

22

Page 23: Network Lab by Armstrong

Recall that rmis code instantiates impl and registers that object with the name “impl”

6. Start the clientjava rmic

Enter the number to generate Fibonacci series, the server receives this request from client, processes it, and returns a result to client.

CLIENT SERVER APPLICATION USING RPCCode:-

INTERFACEimport java.rmi.Remote;import java.rmi.RemoteException;public interface intf extends Remote{int[] fib(int a)throws RemoteException;}

IMPLEMENTATION

import java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject; public class impl extends UnicastRemoteObject implements intf { public impl() throws RemoteException { } public int[] fib(int n)throws RemoteException { int fi=0,a=0,b=1,i; int ab[]=new int[50]; for(i=0;i<n;i++) { fi=fi+a; a=b; b=fi; ab[i]=fi; } return(ab); } }

CLIENT

import java.rmi.*;import java.io.*;public class rmic{

23

Page 24: Network Lab by Armstrong

public static void main(String ar[]){try{int i;BufferedReader br=new BufferedReader(new InputStreamReader(System.in));System.out.println("Enter the server host name");String serip=br.readLine();String url="rmi://"+serip+"/rmis";intf ref=(intf)Naming.lookup(url);while(true){System.out.println("Enter a number:");String st=br.readLine();if(st.equals("end")){break;}else{int n=Integer.parseInt(st);int aa[]=ref.fib(n);for(i=0;i<n;i++){System.out.println(aa[i]);}}}}catch(Exception e){}}}

SERVER

import java.net.UnknownHostException;import java.rmi.Naming;public class rmis{public static void main(String ar[]){try{impl im=new impl();

24

Page 25: Network Lab by Armstrong

Naming.rebind("rmis",im);System.out.println("Binding complete");}catch(Exception e){}}}

OUTPUT:-

SERVER OUTPUTC:\Java\jdk1.5.0\bin>javac intf.javaC:\Java\jdk1.5.0\bin>javac impl.javaC:\Java\jdk1.5.0\bin>javac rmis.javaC:\Java\jdk1.5.0\bin>rmic implC:\Java\jdk1.5.0\bin>start rmiregistryC:\Java\jdk1.5.0\bin>java rmisBinding complete

CLIENT OUTPUTC:\Java\jdk1.5.0\bin>javac rmic.java

C:\Java\jdk1.5.0\bin>java rmicEnter the server host namelocalhostEnter a number:501123Enter a number:exitC:\Java\jdk1.5.0\bin>

Result:Thus the program was executed successfully.

25

Page 26: Network Lab by Armstrong

Ping command using RAW socketEx.7

AIM: To implement Ping command using RAW socket.

ALGORITHM

1. Create a raw socket using socket routine.2. Assign IP address ,port number and the protocol family to the members of struct sockaddr_in for source and destination addresses.3. Build our own packet structure using setsockopt(). 4. Obtain the Hostname and retrieve address using gethostbyname function.5. Fabricate the IP header with standard header structures6. Calculate the Header checksum for integrity.7. Set sending times between source to destination.8. Close socket.

Code:-

#include<iostream.h>#include<stdio.h>#include<sys/types.h>#include<sys/socket.h>#include<netdb.h>#include<netinet/in.h>#include<netinet/in_systm.h>#include<netinet/ip.h>#include<netinet/ip_icmp.h>#include<string.h>#include<arpa/inet.h>int main(int argc, char *argv[]){ int s, i; char buf[400]; struct ip *ip = (struct ip *)buf; struct icmphdr *icmp = (struct icmphdr *)(ip + 1); struct hostent *hp, *hp2; struct sockaddr_in dst; int offset; int on; int num = 100; if(argc < 3) { cout<<"\nUsage: <saddress> <dstaddress> [number]\n"<< argv[0]; cout<<"- saddress is the spoofed source address\n";

26

Page 27: Network Lab by Armstrong

cout<<"- dstaddress is the target\n"; cout<<"- number is the number of packets to send, 100 is the default\n"; exit(1); } /* If enough argument supplied */ if(argc == 4) /* Copy the packet number */ num = atoi(argv[3]); /* Loop based on the packet number */ for(i=1;i<=num;i++) { on = 1; bzero(buf, sizeof(buf)); /* Create RAW socket */ if((s = socket(AF_INET, SOCK_RAW, IPPROTO_RAW)) < 0) { cout<<"socket() error"; /* If something wrong, just exit */ exit(1); } /* socket options, tell the kernel we provide the IP structure */ if(setsockopt(s, IPPROTO_IP, IP_HDRINCL, &on, sizeof(on)) < 0) { cout<<"setsockopt() for IP_HDRINCL error"; exit(1); } if((hp = gethostbyname(argv[2])) == NULL) { if((ip->ip_dst.s_addr = inet_addr(argv[2])) == -1) { fprintf(stderr, "%s: Can't resolve, unknown host.\n", argv[2]); exit(1); } } else bcopy(hp->h_addr_list[0], &ip->ip_dst.s_addr, hp->h_length); /* The following source address just redundant for target to collect */ if((hp2 = gethostbyname(argv[1])) == NULL) { if((ip->ip_src.s_addr = inet_addr(argv[1])) == -1) {

27

Page 28: Network Lab by Armstrong

fprintf(stderr, "%s: Can't resolve, unknown host\n", argv[1]); exit(1); } } else bcopy(hp2->h_addr_list[0], &ip->ip_src.s_addr, hp->h_length); cout<<"Sending to" << inet_ntoa(ip->ip_dst)<<" from spoofed "<< argv[1]; /* Ip structure, check the ip.h */ ip->ip_v = 4; ip->ip_hl = sizeof*ip >> 2; ip->ip_tos = 0; ip->ip_len = htons(sizeof(buf)); ip->ip_id = htons(4321); ip->ip_off = htons(0); ip->ip_ttl = 255; ip->ip_p = 1; ip->ip_sum = 0; /* Let kernel fills in */ dst.sin_addr = ip->ip_dst; dst.sin_family = AF_INET; icmp->type = ICMP_ECHO; icmp->code = 0; /* Header checksum */ icmp->checksum = htons(~(ICMP_ECHO << 8)); for(offset = 0; offset < 65536; offset += (sizeof(buf) - sizeof(*ip))) { ip->ip_off = htons(offset >> 3); if(offset < 65120) ip->ip_off |= htons(0x2000); else ip->ip_len = htons(418); /* make total 65538 */ /* sending time */ if(sendto(s, buf, sizeof(buf), 0, (struct sockaddr *)&dst, sizeof(dst)) < 0) { fprintf(stderr, "offset %d: ", offset); perror("sendto() error"); } else printf("sendto() is OK.\n"); /* IF offset = 0, define our ICMP structure */ if(offset == 0) { icmp->type = 0;

28

Page 29: Network Lab by Armstrong

icmp->code = 0; icmp->checksum = 0; } } /* close socket */ close(s); usleep(30000); } return 0;}

OUTPUT:-

[root@bakawali testraw]# c++ myping.cpp -o myping

[root@bakawali testraw]# ./myping

Usage: ./myping <saddress> <dstaddress> [number]

- saddress is the spoofed source address

- dstaddress is the target address

- number is the number of packets to send, 100 is the default

[root@bakawali testraw]# ./myping 192.16.6.151 192.16.6.23 10000

sendto() is OK.

29

Page 30: Network Lab by Armstrong

sendto() is OK.

...

...

sendto() is OK.

sendto() is OK.

Sending to 192.16.6.151 from spoofed 192.16.6.23

sendto() is OK.

...

Result:Thus the program was executed successfully.

30

Page 31: Network Lab by Armstrong

Packet Capturing and MonitoringEx.8

AIM: To implement Packet Capturing and MonitoringUsing jpcap.

ALGORITHM

Network interface device

1. Find network interface device name using JpcapCaptor.getDeviceList(). 2. Obtain the information about device name, device description, device’s MAC address, subnet and broadcast address.3. Repeat steps 1-2 until available network interface devices.

Sending Packets to Network device

1. Open available network devices for sending packets through that device using JpcapSender.openDevice(). 2. Send the TCP packets using JpcapSender().

Network interface device (Tcpdump.java)Code:-

import jpcap.*;import jpcap.packet.Packet;

class Tcpdump implements PacketReceiver {public void receivePacket(Packet packet) {System.out.println(packet);}

public static void main(String[] args) throws Exception {NetworkInterface[] devices = JpcapCaptor.getDeviceList();if(args.length<1){System.out.println("usage: java Tcpdump <select a number from the following>");

for (int i = 0; i < devices.length; i++) {System.out.println(i+" :"+devices[i].name + "(" + devices[i].description+")");System.out.println(" data link:"+devices[i].datalink_name + "("+ devices[i].datalink_description+")");System.out.print("MAC address:");for (byte b : devices[i].mac_address)

31

Page 32: Network Lab by Armstrong

System.out.print(Integer.toHexString(b&0xff) + ":");System.out.println();for (NetworkInterfaceAddress a : devices[i].addresses)System.out.println(" address:"+a.address + " " + a.subnet + " "+ a.broadcast);}}else{JpcapCaptor jpcap = JpcapCaptor.openDevice(devices[Integer.parseInt(args[0])], 2000, false, 20);

jpcap.loopPacket(-1, new Tcpdump());}}}

Sending Packets to Network device (SendTCP.java)

import java.net.InetAddress;import jpcap.*;import jpcap.packet.EthernetPacket;import jpcap.packet.IPPacket;import jpcap.packet.TCPPacket;

class SendTCP{public static void main(String[] args) throws java.io.IOException{NetworkInterface[] devices = JpcapCaptor.getDeviceList();if(args.length<1){System.out.println("Usage: java SentTCP <device index (e.g., 0, 1..)>");for(int i=0;i<devices.length;i++)System.out.println(i+":"+devices[i].name+"("+devices[i].description+")");System.exit(0);}int index=Integer.parseInt(args[0]);JpcapSender sender=JpcapSender.openDevice(devices[index]);

TCPPacket p=new TCPPacket(12,34,56,78,false,false,false,false,true,true,true,true,10,10);p.setIPv4Parameter(0,false,false,false,0,false, false,false,0,1010101,100,IPPacket.IPPROTO_TCP,InetAddress.getByName("www.microsoft.com"),

32

Page 33: Network Lab by Armstrong

InetAddress.getByName("www.google.com"));p.data=("data").getBytes();

EthernetPacket ether=new EthernetPacket();ether.frametype=EthernetPacket.ETHERTYPE_IP;ether.src_mac=new byte[]{(byte)0,(byte)1,(byte)2,(byte)3,(byte)4,(byte)5};ether.dst_mac=new byte[]{(byte)0,(byte)6,(byte)7,(byte)8,(byte)9,(byte)10};p.datalink=ether;

for(int i=0;i<10;i++)sender.sendPacket(p);}}

Output

C:\ Program Files \Java\JDK16~1.0\bin>javac Tcpdump.javaC:\ Program Files \Java\JDK16~1.0\bin>java Tcpdump 0

1282048961:530746 /207.46.19.254->/209.85.231.104 protocol(6) priority(0) hop(100) offset(0) ident(27061) TCP 12 > 34 seq(56) win(10) S F1282048961:530979 /207.46.19.254->/209.85.231.104 protocol(6) priority(0) hop(100) offset(0) ident(27061) TCP 12 > 34 seq(56) win(10) S F1282048961:531203 /207.46.19.254->/209.85.231.104 protocol(6) priority(0) hop(100) offset(0) ident(27061) TCP 12 > 34 seq(56) win(10) S F1282048961:531425 /207.46.19.254->/209.85.231.104 protocol(6) priority(0) hop(100) offset(0) ident(27061) TCP 12 > 34 seq(56) win(10) S F1282048961:531641 /207.46.19.254->/209.85.231.104 protocol(6) priority(0) hop(100) offset(0) ident(27061) TCP 12 > 34 seq(56) win(10) S F1282048961:531862 /207.46.19.254->/209.85.231.104 protocol(6) priority(0) hop(100) offset(0) ident(27061) TCP 12 > 34 seq(56) win(10) S F1282048961:532080 /207.46.19.254->/209.85.231.104 protocol(6) priority(0) hop(100) offset(0) ident(27061) TCP 12 > 34 seq(56) win(10) S F1282048961:532301 /207.46.19.254->/209.85.231.104 protocol(6) priority(0) hop(100) offset(0) ident(27061) TCP 12 > 34 seq(56) win(10) S F1282048961:532520 /207.46.19.254->/209.85.231.104 protocol(6) priority(0) hop(1

33

Page 34: Network Lab by Armstrong

00) offset(0) ident(27061) TCP 12 > 34 seq(56) win(10) S F1282048961:532740 /207.46.19.254->/209.85.231.104 protocol(6) priority(0) hop(100) offset(0) ident(27061) TCP 12 > 34 seq(56) win(10) S F

Other Window

C:\Program Files\Java\jdk1.6.0\bin>java SendTCP 0

C:\Program Files\Java\jdk1.6.0\bin>

Result:Thus the program was executed successfully.

34

Page 35: Network Lab by Armstrong

CBR over UDP and CBR over TCPEx.9

AIM: To simulate CBR over UDP and CBR over TCP using NS2

ALGORITHM

CBR over UDP

1. Create a simulator object2. Open the NAM trace file3. Define a 'finish' procedure for Close the trace file and Execute NAM on the trace file4. Create topology as two nodes n0 and n1 with a simplex link between them.5. Create a UDP agent and attach it to node n06. Create a CBR traffic source and attach it to UDP agent7. Create a Null agent (a traffic sink) and attach it to node n18. Connect the traffic source with the traffic sink9. Schedule events for the CBR agent10. Call the finish procedure after 3 seconds of simulation time11. Run the simulation

CBR over TCP

1. Create a simulator object2. Open the NAM trace file3. Define a 'finish' procedure for Close the trace file and Execute NAM on the trace file4. Create topology as two nodes n0 and n1 with a simplex link between them.5. Create a tcp0 agent and attach it to node n06. Create a CBR0 traffic source and attach it to tcp0 agent7. Create a TCPSink0 agent (a traffic sink) and attach it to node n18. Connect the traffic source with the traffic sink9. Schedule events for the CBR0 agent10. Call the finish procedure after 3 seconds of simulation time11. Run the simulation

Code:- CBR over UDP

set ns [new Simulator]set tracefile [open out.tr w]$ns trace-all $tracefile

set nf [open out.nam w]$ns namtrace-all $nfproc finish {} { global ns tracefile nf $ns flush-trace

35

Page 36: Network Lab by Armstrong

#Close the NAM trace file close $nfclose $tracefile #Execute NAM on the trace file exec nam out.nam & exit 0}set n0 [$ns node]set n1 [$ns node]$ns simplex-link $n0 $n1 1Mb 10ms DropTail

set udp0 [new Agent/UDP]$ns attach-agent $n0 $udp0set cbr [new Application/Traffic/CBR]$cbr attach-agent $udp0set null0 [new Agent/Null]$ns attach-agent $n1 $null0$ns connect $udp0 $null0

$ns at 1.0 "$cbr start"$ns at 3.0 "finish"

$ns run

36

Page 37: Network Lab by Armstrong

OUTPUT:-

Code:- CBR over TCP

set ns [new Simulator]set tracefile [open out.tr w]$ns trace-all $tracefile

set nf [open out.nam w]$ns namtrace-all $nfproc finish {} { global ns tracefile nf $ns flush-trace #Close the NAM trace file close $nfclose $tracefile #Execute NAM on the trace file

37

Page 38: Network Lab by Armstrong

exec nam out.nam & exit 0}set n0 [$ns node]set n1 [$ns node]$ns simplex-link $n0 $n1 1Mb 10ms DropTail

set tcp [new Agent/TCP]$ns attach-agent $n0 $tcpset cbr [new Application/Traffic/CBR]$cbr attach-agent $tcpset tcp0 [new Agent/TCP]$ns attach-agent $n1 $tcp0$ns connect $tcp $tcp0

$ns at 1.0 "$cbr start"$ns at 3.0 "finish"

$ns run

38

Page 39: Network Lab by Armstrong

OUTPUT:-

Result:Thus the program was executed successfully.

39

Page 40: Network Lab by Armstrong

Implementing Routing protocols using NS2Ex.10

AIM: To Implement Routing protocols using NS2

ALGORITHM

1. Create a simulator object and Define different colors for data flows (for NAM)2. Open the NAM trace file3. Define a 'finish' procedure for Close the trace file and Execute NAM on the trace file4. Create topology as four nodes n0, n1, n2 and n3 with a duplex link between them.5. Give node position (for NAM)6. Set Queue Size of link (n2-n3) to 107. Monitor the queue for link (n2-n3). (for NAM)8. Setup TCP connection and UDP connection8. Setup a FTP over TCP connection and CBR over UDP connection9. Schedule events for the CBR and FTP agents10. Call the finish procedure after 5 seconds of simulation time11. Print CBR packet size and interval12. Run the simulation

Code:-

#Create a simulator objectset ns [new Simulator]

#Define different colors for data flows (for NAM)$ns color 1 Blue$ns color 2 Red

#Open the NAM trace fileset nf [open out.nam w]$ns namtrace-all $nf

#Define a 'finish' procedureproc finish {} { global ns nf $ns flush-trace #Close the NAM trace file close $nf #Execute NAM on the trace file exec nam out.nam & exit 0}

40

Page 41: Network Lab by Armstrong

#Create four nodesset n0 [$ns node]set n1 [$ns node]set n2 [$ns node]set n3 [$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 1.7Mb 20ms DropTail

#Set Queue Size of link (n2-n3) to 10$ns queue-limit $n2 $n3 10

#Give node position (for NAM)$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

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

#Setup a TCP connectionset tcp [new Agent/TCP]$tcp set class_ 2$ns attach-agent $n0 $tcpset sink [new Agent/TCPSink]$ns attach-agent $n3 $sink$ns connect $tcp $sink$tcp set fid_ 1

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

#Setup a UDP connectionset 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_ 2

41

Page 42: Network Lab by Armstrong

#Setup a CBR over UDP connectionset cbr [new Application/Traffic/CBR]$cbr attach-agent $udp$cbr set type_ CBR$cbr set packet_size_ 1000$cbr set rate_ 1mb$cbr set random_ false

#Schedule events for the CBR and FTP agents$ns at 0.1 "$cbr start"$ns at 1.0 "$ftp start"$ns at 4.0 "$ftp stop"$ns at 4.5 "$cbr stop"

#detach tcp and sink agents (not really necessary)$ns at 4.5 "$ns detach-agent $n0 $tcp ; $ns detach-agent $n3 $sink"

#Call the finish procedure after 5 seconds of simulation time$ns at 5.0 "finish"

#Print CBR packet size and intervalputs "CBR packet size = [$cbr set packet_size_]"puts "CBR interval = [$cbr set interval_]"

#Run the simulation$ns run

42

Page 43: Network Lab by Armstrong

OUTPUT:-

Result:Thus the program was executed successfully.

43

Page 44: Network Lab by Armstrong

Performance comparison of routing protocolsEx.11

AIM: To compare the performance of Routing protocols using NS2

ALGORITHM

1. Create a simulator object and Define different colors for data flows (for NAM)2. Open the NAM trace file3. Define a 'finish' procedure for Close the trace file and Execute NAM on the trace file.4. Call xgraph to display the results.5. Create topology as five nodes as n0, n1, n2, n3 and n4. Connect a duplex link between them.6. Define a procedure 'attach-expoo-traffic' that attaches a UDP agent to a previously created node 'node' and attaches an Expoo traffic generator to the agent with the characteristic values 'size' for packet size 'burst' for burst time, 'idle' for idle time and 'rate' for burst peak rate. The procedure connects the source with the previously defined traffic sink 'sink' and returns the source object.7. Define a procedure 'record' which periodically records the bandwidth received by the three traffic sinks sink0/1/2 and writes it to the three files f0/1/2.8. Calculate the bandwidth (in MBit/s) and write it to the files.9. Re-schedule the procedure 'record' at regular intervals(0.5 seconds).10. Create three traffic sources, start and stop traffic sources at regular intervals respectively.11. Call the finish procedure after 60 seconds of simulation time12. Run the simulation

Code:-

#Create a simulator objectset ns [new Simulator]#Open the output filesset f0 [open out0.tr w]set f1 [open out1.tr w]set f2 [open out2.tr w]#Create 5 nodesset n0 [$ns node]set n1 [$ns node]set n2 [$ns node]set n3 [$ns node]set n4 [$ns node]#Connect the nodes$ns duplex-link $n0 $n3 1Mb 100ms DropTail$ns duplex-link $n1 $n3 1Mb 100ms DropTail$ns duplex-link $n2 $n3 1Mb 100ms DropTail$ns duplex-link $n3 $n4 1Mb 100ms DropTail

44

Page 45: Network Lab by Armstrong

#Define a 'finish' procedureproc finish {} {global f0 f1 f2#Close the output filesclose $f0close $f1close $f2#Call xgraph to display the resultsexec xgraph out0.tr out1.tr out2.tr -geometry 800x400 &exit 0}

#Define a procedure that attaches a UDP agent to a #previously created node 'node' and attaches an Expoo #traffic generator to the agent with the#characteristic values 'size' for packet size 'burst' for #burst time,#'idle' for idle time and 'rate' for burst peak rate. The #procedure connects#the source with the previously defined traffic sink 'sink' #and returns the source object.proc attach-expoo-traffic { node sink size burst idle rate } {#Get an instance of the simulatorset ns [Simulator instance]#Create a UDP agent and attach it to the nodeset source [new Agent/UDP]$ns attach-agent $node $source#Create an Expootraffic agent and set its configuration #parametersset traffic [new Application/Traffic/Exponential]$traffic set packetSize_ $size$traffic set burst_time_ $burst$traffic set idle_time_ $idle$traffic set rate_ $rate# Attach traffic source to the traffic generator$traffic attach-agent $source#Connect the source and the sink$ns connect $source $sinkreturn $traffic}

#Define a procedure which periodically records the #bandwidth received by the

45

Page 46: Network Lab by Armstrong

#three traffic sinks sink0/1/2 and writes it to the three #files f0/1/2.proc record {} {global sink0 sink1 sink2 f0 f1 f2#Get an instance of the simulatorset ns [Simulator instance]#Set the time after which the procedure should be called #againset time 0.5#How many bytes have been received by the traffic sinks?set bw0 [$sink0 set bytes_]set bw1 [$sink1 set bytes_]set bw2 [$sink2 set bytes_]#Get the current timeset now [$ns now]#Calculate the bandwidth (in MBit/s) and write it to the filesputs $f0 "$now [expr $bw0/$time*8/1000000]"puts $f1 "$now [expr $bw1/$time*8/1000000]"puts $f2 "$now [expr $bw2/$time*8/1000000]"#Reset the bytes_ values on the traffic sinks$sink0 set bytes_ 0$sink1 set bytes_ 0$sink2 set bytes_ 0#Re-schedule the procedure$ns at [expr $now+$time] "record"}

#Create three traffic sinks and attach them to the node n4set sink0 [new Agent/LossMonitor]set sink1 [new Agent/LossMonitor]set sink2 [new Agent/LossMonitor]$ns attach-agent $n4 $sink0$ns attach-agent $n4 $sink1$ns attach-agent $n4 $sink2#Create three traffic sourcesset source0 [attach-expoo-traffic $n0 $sink0 200 2s 1s 100k]set source1 [attach-expoo-traffic $n1 $sink1 200 2s 1s 200k]set source2 [attach-expoo-traffic $n2 $sink2 200 2s 1s 300k]#Start logging the received bandwidth$ns at 0.0 "record"#Start the traffic sources$ns at 10.0 "$source0 start"$ns at 10.0 "$source1 start"$ns at 10.0 "$source2 start"#Stop the traffic sources

46

Page 47: Network Lab by Armstrong

$ns at 50.0 "$source0 stop"$ns at 50.0 "$source1 stop"$ns at 50.0 "$source2 stop"#Call the finish procedure after 60 seconds simulation time$ns at 60.0 "finish"#Run the simulation$ns run

OUTPUT:-

Result:Thus the program was executed successfully.

47

Page 48: Network Lab by Armstrong

Ex.12Sliding Window Protocol using NS2

AIM: To implement Sliding Window Protocol using NS2

ALGORITHM

Simple sliding window without any packet loss

1. Create a simulator object2. Open the NAM trace file3. Define a 'init' procedure for open the trace file and open NAM on the trace file4. Create setup sliding window topology as 6 nodes with a connection of simplex link between them.5. Define a 'finish' procedure for close the trace file and Execute NAM on the trace file6. Define a 'run' procedure for TCP between n_(0) & n_(4) and CBR traffic between n_(1) & n_(5) and set packet size and interval.9. Schedule events for the CBR0, FTP and self10. Run the simulation

Simple sliding window with packet loss

1. Create a simulator object2. Open the NAM trace file3. Define a 'init' procedure for open the trace file and open NAM on the trace file4. Create setup sliding window topology as 6 nodes with a connection of simplex link between them.5. Define a 'finish' procedure for close the trace file and Execute NAM on the trace file6. Define a 'run' procedure for TCP between n_(0) & n_(4) and CBR traffic between n_(1) & n_(5)9. Schedule events for the CBR0, FTP and self10. Run the simulation

CODE:-

#Agent/TCP set tcpTick_ 0.1# The default for tcpTick_ is being changed to reflect a changing reality.Agent/TCP set rfc2988_ false# The default for rfc2988_ is being changed to true.# FOR UPDATING GLOBAL DEFAULTS:Agent/TCP set precisionReduce_ false ; # default changed on 2006/1/24.Agent/TCP set rtxcur_init_ 6.0 ; # Default changed on 2006/01/21Agent/TCP set updated_rttvar_ false ; # Variable added on 2006/1/21Agent/TCP set minrto_ 1# default changed on 10/14/2004.Agent/TCP set useHeaders_ false# The default is being changed to useHeaders_ true.Agent/TCP set windowInit_ 1# The default is being changed to 2.

48

Page 49: Network Lab by Armstrong

Agent/TCP set singledup_ 0# The default is being changed to 1

# This test suite is for validating sliding window# To run all tests: test-all-sliding-window# to run individual test:# ns test-suite-sliding-window.tcl sliding-normal# ns test-suite-sliding-window.tcl sliding-loss## To view a list of available test to run with this script:# ns test-suite-sliding-window.tcl## Each of the tests uses 6 nodes #

Class TestSuite

Class Test/sliding-normal -superclass TestSuite# Simple sliding window without any packet loss

Class Test/sliding-loss -superclass TestSuite# Simple sliding window with packet loss

proc usage {} {global argv0puts stderr "usage: ns $argv0 <tests> "puts "Valid <tests> : sliding-normal sliding-loss"exit 1

}

TestSuite instproc init {} {

$self instvar ns_ n_

set ns_ [new Simulator] $ns_ trace-all [open temp.rands w] $ns_ namtrace-all [open temp.rands.nam w]

# setup sliding window topology foreach i " 0 1 2 3 4 5" {

set n_($i) [$ns_ node] }

$ns_ duplex-link $n_(0) $n_(2) 1Mb 20ms DropTail $ns_ duplex-link $n_(1) $n_(2) 1Mb 20ms DropTail $ns_ duplex-link $n_(2) $n_(3) 0.5Mb 20ms DropTail $ns_ duplex-link $n_(3) $n_(4) 1Mb 20ms DropTail $ns_ duplex-link $n_(3) $n_(5) 1Mb 20ms DropTail

$ns_ duplex-link-op $n_(0) $n_(2) orient right-down $ns_ duplex-link-op $n_(1) $n_(2) orient right-up $ns_ duplex-link-op $n_(2) $n_(3) orient right $ns_ duplex-link-op $n_(3) $n_(4) orient right-up $ns_ duplex-link-op $n_(3) $n_(5) orient right-down

$ns_ duplex-link-op $n_(2) $n_(3) queuePos 0.5

49

Page 50: Network Lab by Armstrong

}

TestSuite instproc finish {} {$self instvar ns_global quiet

$ns_ flush-trace if { !$quiet } { puts "running nam..." exec nam temp.rands.nam & }

exit 0}

Test/sliding-normal instproc init {flag} {$self instvar ns_ testName_ flag_set testName_ sliding-normalset flag_ $flag$self next

}

Test/sliding-normal instproc run {} {

$self instvar ns_ n_ $ns_ queue-limit $n_(2) $n_(3) 50

### TCP between n_(0) & n_(4) Agent/TCP set maxcwnd_ 8 set sliding [new Agent/TCP/SlidingWindow] $ns_ attach-agent $n_(0) $sliding set sink [new Agent/TCPSink/SlidingWindowSink] $ns_ attach-agent $n_(4) $sink $ns_ connect $sliding $sink set ftp [new Application/FTP] $ftp attach-agent $sliding

### CBR traffic between n_(1) & n_(5) set udp0 [new Agent/UDP] $ns_ attach-agent $n_(1) $udp0 set cbr0 [new Application/Traffic/CBR] $cbr0 set packetSize_ 500 $cbr0 set interval_ 0.01 $cbr0 attach-agent $udp0 set null0 [new Agent/Null] $ns_ attach-agent $n_(5) $null0 $ns_ connect $udp0 $null0

### setup operation$ns_ at 0.1 "$cbr0 start"

$ns_ at 1.1 "$cbr0 stop" $ns_ at 0.2 "$ftp start" $ns_ at 1.1 "$ftp stop"

$ns_ at 1.2 "$self finish"$ns_ run

}

Test/sliding-loss instproc init {flag} {

50

Page 51: Network Lab by Armstrong

$self instvar ns_ testName_ flag_set testName_ sliding-lossset flag_ $flag$self next

}

Test/sliding-loss instproc run {} {

$self instvar ns_ n_ $ns_ queue-limit $n_(2) $n_(3) 10

### TCP between n_(0) & n_(4) Agent/TCP set maxcwnd_ 8 set sliding [new Agent/TCP/SlidingWindow] $ns_ attach-agent $n_(0) $sliding set sink [new Agent/TCPSink/SlidingWindowSink] $ns_ attach-agent $n_(4) $sink $ns_ connect $sliding $sink set ftp [new Application/FTP] $ftp attach-agent $sliding

### CBR traffic between n_(1) & n_(5) set udp0 [new Agent/UDP] $ns_ attach-agent $n_(1) $udp0 set cbr0 [new Application/Traffic/CBR] $cbr0 attach-agent $udp0 set null0 [new Agent/Null] $ns_ attach-agent $n_(5) $null0 $ns_ connect $udp0 $null0

### setup operation$ns_ at 0.1 "$cbr0 start"

$ns_ at 1.1 "$cbr0 stop" $ns_ at 0.2 "$ftp start" $ns_ at 1.1 "$ftp stop"

$ns_ at 1.2 "$self finish"$ns_ run

}

proc runtest {arg} {global quietset quiet 0

set b [llength $arg]if {$b == 1} {

set test $arg} elseif {$b == 2} {

set test [lindex $arg 0] if {[lindex $arg 1] == "QUIET"} {

set quiet 1 }} else {

usage}switch $test {

sliding-normal - sliding-loss {

51

Page 52: Network Lab by Armstrong

set t [new Test/$test 1]}default {

stderr "Unknown test $test"exit 1

}}$ns run

}global argv arg0runtest $argv

OUTPUT:-

[root@localhost root]# ns test-suite-sliding-window.tcl

usage: ns test-suite-sliding-window.tcl <tests>

Valid <tests> : sliding-normal sliding-loss

[root@localhost root]# vi test-suite-sliding-window.tcl

[root@localhost root]# ns test-suite-sliding-window.tcl sliding-normal

[root@localhost root]# ns test-suite-sliding-window.tcl sliding-loss

[root@localhost root]#

Result:Thus the program was executed successfully.

52