Network Lab MANNUL

Embed Size (px)

Citation preview

  • 8/3/2019 Network Lab MANNUL

    1/58

    TCP - CHAT PROGRAM

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

  • 8/3/2019 Network Lab MANNUL

    2/58

    CODE:

    Server:

    #include

    #include#include#include#include#include#include#include#include#include#include# define MAX 100

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

  • 8/3/2019 Network Lab MANNUL

    3/58

    cout

  • 8/3/2019 Network Lab MANNUL

    4/58

    Client:

    #include#include#include#include#include#include#include#include#include#include

    #include#include# 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

  • 8/3/2019 Network Lab MANNUL

    5/58

    cout

  • 8/3/2019 Network Lab MANNUL

    6/58

    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 4567

    Enter the message for server: heymessage hiEnter the message for server:byemessage bye

    Result:

    Thus the program was executed successfully.

  • 8/3/2019 Network Lab MANNUL

    7/58

    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 specificport 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 clients 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

  • 8/3/2019 Network Lab MANNUL

    8/58

    SERVER PROGRAM SOURCE CODE

    #include#includemain( )

    {struct sockaddr_in sa;struct sockaddr_in cli;int sockfd,coontfd;int len,ch;char str[100];time_t tick;sockfd=socket(AF_INET,SOCK_STREAM,0);if(socket

  • 8/3/2019 Network Lab MANNUL

    9/58

    CLIENT PROGRAM SOURCE CODE#include#includemain(){

    struct sockaddr_in sa,cli;int n,sockfd;int len;char buff[100];sockfd=socket(AF_INET,SOCK_STREAM,0);if(sockfd

  • 8/3/2019 Network Lab MANNUL

    10/58

    Output

    SERVER SIDE OUTPUTSocket OpenedBinded successfullyAccepted

    CLIENT SIDE OUTPUT WITH SERVER TIMESocket is OpenedConnected successfullyMessage Read Mon Jan 22 15:09:19 2007

    RESULT:Thus the program for getting the day and time of the server using TCP has beencreated and verified.

  • 8/3/2019 Network Lab MANNUL

    11/58

    DOMAIN NAME SERVER using TCP

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

  • 8/3/2019 Network Lab MANNUL

    12/58

    Source Code :-

    server:

    #include#include#include#include#include#include#include#include#include#include#define SER_PORT 6022

    int main(){int a, sersock, newsock;char str2[100], host[25];void *buf, *buf2;struct sockaddr_in seraddr;struct sockaddr_in clinfo;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))

  • 8/3/2019 Network Lab MANNUL

    13/58

    exit(0);}elsecout

  • 8/3/2019 Network Lab MANNUL

    14/58

    }cout host;write(clisock, host, strlen(host)+1);read(clisock, str2, sizeof(str2));

    cout

  • 8/3/2019 Network Lab MANNUL

    15/58

    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.

  • 8/3/2019 Network Lab MANNUL

    16/58

    DOMAIN NAME SERVER using UDP

    Ex.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#include#include#include#include#include#include#include#include#includevoid dg_echo(int sockfd,struct sockaddr* pcliaddr,socklen_t clilen);int main(int argc,char **argv){

  • 8/3/2019 Network Lab MANNUL

    17/58

    int sockfd;char mesg2[100];struct hostent *hp;

    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

  • 8/3/2019 Network Lab MANNUL

    18/58

    if(argc!=2){cout

  • 8/3/2019 Network Lab MANNUL

    19/58

    Create a RAW socket with UDP protocol

    Ex.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 count8. Close socket.

    Code:-

    #include #include #include #include #include #include // 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;

  • 8/3/2019 Network Lab MANNUL

    20/58

    };// 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 all16 bit words in the //header. For purposes of computing the checksum, the //value of thechecksum 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){cout

  • 8/3/2019 Network Lab MANNUL

    21/58

    coutiph_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]));udp->udph_len = htons(sizeof(struct udpheader));

  • 8/3/2019 Network Lab MANNUL

    22/58

    // Calculate the checksum for integrityip->iph_chksum = csum((unsigned short *)buffer, sizeof(struct ipheader) + sizeof(structudpheader));// 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

  • 8/3/2019 Network Lab MANNUL

    23/58

    OUTPUT:-

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

    - Usage ./rawudp [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.

  • 8/3/2019 Network Lab MANNUL

    24/58

    Client server application Using RPCEx.6

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

    ALGORITHM1. 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. Allremote methods can throw a RemoteException.

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

    (iii) The third source file is rmis.java, contains main program of the servermachine. Its primary function is to update the RMI registry on that machine. This is done byusing the rebind() method of the Naming class. The first argument to the rebind() method isa 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 thisdistributed 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 callsinitiated 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, performdeserialization, and invoke the appropriate code on the server. Theskeleton mechanism is not required for Java2 code.

    (iii)

    To generate stubs and skeletons, use a tool called RMI complier, which isinvoked from the command tool asrmic impl

    This command generates two new lines impl_Skel.class(skeleton) andimpl_Stub.class(stub).

    3. Install files on the client and server machines. (Note:- Client and server is in a singlemachine, 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 machine

    4. Start the RMI registry on the server machine (it maps names to object referenceaccessing the remote names registered on the server and a security manager forRMI(Remote Method Invocation)

    start rmiregistry5. Start the serve

    java rmisRecall that rmis code instantiates impl and registers that object with the nameimpl

  • 8/3/2019 Network Lab MANNUL

    25/58

    6. Start the clientjava rmic

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

    CLIENT SERVER APPLICATION USING RPCCode:-

    INTERFACE

    import 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

  • 8/3/2019 Network Lab MANNUL

    26/58

    {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

  • 8/3/2019 Network Lab MANNUL

    27/58

    System.out.println("Binding complete");}catch(Exception e){}

    }}

  • 8/3/2019 Network Lab MANNUL

    28/58

    OUTPUT:-

    SERVER OUTPUT

    C:\Java\jdk1.5.0\bin>javac intf.javaC:\Java\jdk1.5.0\bin>javac impl.java

    C:\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 OUTPUT

    C:\Java\jdk1.5.0\bin>javac rmic.java

    C:\Java\jdk1.5.0\bin>java rmic

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

    Result:

    Thus the program was executed successfully.

  • 8/3/2019 Network Lab MANNUL

    29/58

    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 structures

    6. Calculate the Header checksum for integrity.7. Set sending times between source to destination.8. Close socket.

    Code:-

    #include#include#include#include#include#include#include#include#include#include#includeint 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)

  • 8/3/2019 Network Lab MANNUL

    30/58

    {cout

  • 8/3/2019 Network Lab MANNUL

    31/58

    }}else

    bcopy(hp2->h_addr_list[0], &ip->ip_src.s_addr, hp->h_length);coutip_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 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");

    }elseprintf("sendto() is OK.\n");/* IF offset = 0, define our ICMP structure */if(offset == 0){icmp->type = 0;icmp->code = 0;icmp->checksum = 0;}}/* close socket */close(s);

  • 8/3/2019 Network Lab MANNUL

    32/58

    usleep(30000);}return 0;

    }

  • 8/3/2019 Network Lab MANNUL

    33/58

    OUTPUT:-

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

    [root@bakawali testraw]# ./myping

    Usage: ./myping [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.

    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.

  • 8/3/2019 Network Lab MANNUL

    34/58

    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, devices 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 usingJpcapSender.openDevice().2. Send the TCP packets using JpcapSender().

  • 8/3/2019 Network Lab MANNUL

    35/58

    Network interface device

    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

  • 8/3/2019 Network Lab MANNUL

    36/58

    {public static void main(String[] args) throws java.io.IOException{NetworkInterface[] devices = JpcapCaptor.getDeviceList();if(args.length/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(1

  • 8/3/2019 Network Lab MANNUL

    37/58

    00) 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 F

    1282048961:532520 /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: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.

  • 8/3/2019 Network Lab MANNUL

    38/58

    CBR over UDP and CBR over TCP

    Ex.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 eventsfor 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 eventsfor the CBR0 agent10. Call the finish procedure after 3 seconds of simulation time11. Run the simulation

  • 8/3/2019 Network Lab MANNUL

    39/58

    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#Close the NAM trace fileclose $nf

    close $tracefile#Execute NAM on the trace fileexec 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

  • 8/3/2019 Network Lab MANNUL

    40/58

    OUTPUT:-

  • 8/3/2019 Network Lab MANNUL

    41/58

    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 fileclose $nf

    close $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 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

  • 8/3/2019 Network Lab MANNUL

    42/58

    OUTPUT:-

    Result:

    Thus the program was executed successfully.

  • 8/3/2019 Network Lab MANNUL

    43/58

    Implementing Routing protocols using NS2

    Ex.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 10

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

  • 8/3/2019 Network Lab MANNUL

    44/58

    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 fileclose $nf#Execute NAM on the trace fileexec nam out.nam &exit 0

    }

    #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

  • 8/3/2019 Network Lab MANNUL

    45/58

    #Setup a TCP connectionset tcp [new Agent/TCP]$tcp set class_ 2$ns attach-agent $n0 $tcp

    set 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

    #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 interval

  • 8/3/2019 Network Lab MANNUL

    46/58

    puts "CBR packet size = [$cbr set packet_size_]"puts "CBR interval = [$cbr set interval_]"

    #Run the simulation$ns run

  • 8/3/2019 Network Lab MANNUL

    47/58

    OUTPUT:-

    Result:

    Thus the program was executed successfully.

  • 8/3/2019 Network Lab MANNUL

    48/58

    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 betweenthem.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 characteristicvalues 'size' for packet size 'burst' for burst time, 'idle' for idle time and 'rate' for burst peakrate. The procedure connects the source with the previously defined traffic sink 'sink' andreturns the source object.7. Define a procedure 'record' which periodically records the bandwidth received by thethree 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 intervalsrespectively.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

  • 8/3/2019 Network Lab MANNUL

    49/58

    $ns duplex-link $n2 $n3 1Mb 100ms DropTail$ns duplex-link $n3 $n4 1Mb 100ms DropTail#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#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]

  • 8/3/2019 Network Lab MANNUL

    50/58

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

  • 8/3/2019 Network Lab MANNUL

    51/58

    OUTPUT:-

    Result:

    Thus the program was executed successfully.

  • 8/3/2019 Network Lab MANNUL

    52/58

    Ex.12

    Sliding 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 linkbetween 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 eventsfor 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 linkbetween 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 eventsfor the CBR0, FTP and self10. Run the simulation

  • 8/3/2019 Network Lab MANNUL

    53/58

    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.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 "puts "Valid : sliding-normal sliding-loss"exit 1

    }

  • 8/3/2019 Network Lab MANNUL

    54/58

    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}

    TestSuite instproc finish {} {$self instvar ns_global quiet

    $ns_ flush-traceif { !$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

  • 8/3/2019 Network Lab MANNUL

    55/58

    $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_ 8set sliding [new Agent/TCP/SlidingWindow]$ns_ attach-agent $n_(0) $slidingset sink [new Agent/TCPSink/SlidingWindowSink]$ns_ attach-agent $n_(4) $sink$ns_ connect $sliding $sinkset 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) $udp0set cbr0 [new Application/Traffic/CBR]$cbr0 set packetSize_ 500$cbr0 set interval_ 0.01$cbr0 attach-agent $udp0set 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} {$self instvar ns_ testName_ flag_set testName_ sliding-lossset flag_ $flag$self next

    }

    Test/sliding-loss instproc run {} {

  • 8/3/2019 Network Lab MANNUL

    56/58

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

    ### TCP between n_(0) & n_(4)

    Agent/TCP set maxcwnd_ 8set sliding [new Agent/TCP/SlidingWindow]$ns_ attach-agent $n_(0) $slidingset sink [new Agent/TCPSink/SlidingWindowSink]$ns_ attach-agent $n_(4) $sink$ns_ connect $sliding $sinkset 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) $udp0set cbr0 [new Application/Traffic/CBR]$cbr0 attach-agent $udp0set 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

  • 8/3/2019 Network Lab MANNUL

    57/58

    }switch $test {

    sliding-normal -sliding-loss {

    set t [new Test/$test 1]

    }default {stderr "Unknown test $test"exit 1

    }}$ns run

    }global argv arg0runtest $argv

  • 8/3/2019 Network Lab MANNUL

    58/58

    OUTPUT:-

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

    usage: ns test-suite-sliding-window.tcl

    Valid : 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.