+ All Categories

CN LAB

Date post: 04-Sep-2015
Category:
Upload: shannon-ross
View: 216 times
Download: 0 times
Share this document with a friend
Description:
Manual
92
EX. NO: 1.a TCP SOCKETS DATE: TCP ECHO SERVER / CLIENT AIM: To implement echo client server using TCP/IP ALGORITHM Server 1. Create a server socket and bind it to port. 2. Listen for new connection and when a connection arrives, accept it. 3. Read the data from client. 4. Echo the data back to the client. 5. Repeat steps 4-5 until „bye‟ or „null‟ is read. 6. Close all streams. 7. Close the server socket. 8. Stop. Client 1. Create a client socket and connect it to the server‟s port number. 2. Get input from user. 3. If equal to bye or null, then go to step 7. 4. Send user data to the server. 5. Display the data echoed by the server. 6. Repeat steps 2-4. 7. Close the input and output streams. 8. Close the client socket. 9. Stop.
Transcript
  • EX. NO: 1.a TCP SOCKETS

    DATE: TCP ECHO SERVER / CLIENT

    AIM:

    To implement echo client server using TCP/IP

    ALGORITHM

    Server

    1. Create a server socket and bind it to port.

    2. Listen for new connection and when a connection arrives, accept it.

    3. Read the data from client.

    4. Echo the data back to the client.

    5. Repeat steps 4-5 until bye or null is read.

    6. Close all streams.

    7. Close the server socket.

    8. Stop.

    Client

    1. Create a client socket and connect it to the servers port number.

    2. Get input from user.

    3. If equal to bye or null, then go to step 7.

    4. Send user data to the server.

    5. Display the data echoed by the server.

    6. Repeat steps 2-4.

    7. Close the input and output streams.

    8. Close the client socket.

    9. Stop.

  • PROGRAM:

    // TCP Echo Server--tcpechoserver.java

    import java.net.*;

    import java.io.*;

    public class tcpechoserver

    {

    public static void main(String[] arg) throws IOException

    {

    ServerSocket sock = null;

    BufferedReader fromClient = null;

    OutputStreamWriter toClient = null;

    Socket client = null;

    try

    {

    sock = new ServerSocket(4000); System.out.println("Server Ready");

    client = sock.accept(); System.out.println("Client Connected");

    fromClient = new BufferedReader(new

    InputStreamReader(client.getInputStream()));

    toClient = new OutputStreamWriter(client.getOutputStream());

    String line;

    while (true)

    {

    line = fromClient.readLine();

    if ( (line == null) || line.equals("bye"))

    break;

    System.out.println ("Client [ " + line + " ]");

    toClient.write("Server [ "+ line +" ]\n");

    toClient.flush();

    }

    fromClient.close();

    toClient.close();

    client.close();

    sock.close();

    System.out.println("Client Disconnected");

    }

    catch (IOException ioe)

    {

    System.err.println(ioe);

    }

    }

    }

  • //TCP Echo Client--tcpechoclient.java

    import java.net.*;

    import java.io.*;

    public class tcpechoclient

    {

    public static void main(String[] args) throws IOException

    {

    BufferedReader fromServer = null, fromUser = null;

    PrintWriter toServer = null;

    Socket sock = null;

    try

    {

    if (args.length == 0)

    sock = new Socket(InetAddress.getLocalHost(),4000);

    else

    sock = new Socket(InetAddress.getByName(args[0]),4000);

    fromServer = new BufferedReader(new

    InputStreamReader(sock.getInputStream()));

    fromUser = new BufferedReader(new InputStreamReader(System.in));

    toServer = new PrintWriter(sock.getOutputStream(),true);

    String Usrmsg, Srvmsg;

    System.out.println("Type \"bye\" to quit");

    while (true)

    {

    System.out.print("Enter msg to server : ");

    Usrmsg = fromUser.readLine();

    if (Usrmsg==null || Usrmsg.equals("bye"))

    {

    toServer.println("bye"); break;

    }

    else

    toServer.println(Usrmsg);

    Srvmsg = fromServer.readLine();

    System.out.println(Srvmsg);

    }

    fromUser.close();

    fromServer.close();

    toServer.close();

    sock.close();

    }

    catch (IOException ioe)

    {

    System.err.println(ioe);

    }

  • OUTPUT

    Server:

    $ javac tcpechoserver.java

    $ java tcpechoserver

    Server Ready Client Connected Client [ hello ]

    Client [ how are you ] Client [ i am fine ] Client [ ok ]

    Client Disconnected

    Client :

    $ javac tcpechoclient.java

    $ java tcpechoclient

    Type "bye" to quit

    Enter msg to server : hello

    Server [ hello ]

    Enter msg to server : how are you

    Server [ how are you ]

    Enter msg to server : i am fine

    Server [ i am fine ]

    Enter msg to server : ok

    Server [ ok ]

    Enter msg to server : bye

    RESULT

    Thus data from client to server is echoed back to the client to check reliability/noise level

    of the channel.

  • EX. NO: 1.b TCP SOCKETS DATE AND TIME SERVER / CLIENT

    DATE:

    AIM:

    To implement date and time display from client to server using TCP Sockets

    ALGORITHM:

    Server

    1. Create a server socket and bind it to port.

    2. Listen for new connection and when a connection arrives, accept it.

    3. Send servers date and time to the client.

    4. Read clients IP address sent by the client.

    5. Display the client details.

    6. Repeat steps 2-5 until the server is terminated.

    7. Close all streams.

    8. Close the server socket.

    9. Stop.

    Client

    1. Create a client socket and connect it to the servers port number.

    2. Retrieve its own IP address using built-in function.

    3. Send its address to the server.

    4. Display the date & time sent by the server.

    5. Close the input and output streams.

    6. Close the client socket.

    7. Stop.

  • PROGRAM:

    //TCP Date Server--tcpdateserver.java

    import java.net.*;

    import java.io.*;

    import java.util.*;

    class tcpdateserver

    {

    public static void main(String arg[])

    {

    ServerSocket ss = null;

    Socket cs;

    PrintStream ps;

    BufferedReader dis;

    String inet;

    try

    { ss = new ServerSocket(4444);

    System.out.println("Press Ctrl+C to quit");

    while(true)

    {

    cs = ss.accept();

    ps = new PrintStream(cs.getOutputStream());

    Date d = new Date();

    ps.println(d);

    dis = new BufferedReader(new

    InputStreamReader(cs.getInputStream()));

    inet = dis.readLine();

    System.out.println("Client System/IP address is :"+ inet);

    ps.close();

    dis.close();

    }

    }

    catch(IOException e)

    {

    System.out.println("The exception is :" + e);

    }

    }

    }

  • //TCP Date Client--tcpdateclient.java

    import java.net.*;

    import java.io.*;

    class tcpdateclient

    {

    public static void main (String args[])

    {

    Socket soc;

    BufferedReader dis;

    String sdate;

    PrintStream ps;

    try

    {

    InetAddress ia = InetAddress.getLocalHost();

    if (args.length == 0)

    soc = new Socket(InetAddress.getLocalHost(),4444);

    else

    soc = new Socket(InetAddress.getByName(args[0]),4444);

    dis = new BufferedReader(new

    InputStreamReader(soc.getInputStream()));

    sdate=dis.readLine();

    System.out.println("The date/time on server is : " +sdate);

    ps = new PrintStream(soc.getOutputStream());

    ps.println(ia);

    ps.close(); catch(IOException e)

    {

    System.out.println("THE EXCEPTION is :" + e);

    } } }

  • OUTPUT

    Server:

    $ javac tcpdateserver.java

    $ java tcpdateserver

    Press Ctrl+C to quit

    Client System/IP address is : localhost.localdomain/127.0.0.1

    Client System/IP address is : localhost.localdomain/127.0.0.1

    Client:

    $ javac tcpdateclient.java

    $ java tcpdateclient

    The date/time on server is: Wed Feb 06 07:12:03 GMT 2015

    RESULT:

    Thus the program for implementing to display date and time from client to server using

    TCP Sockets was executed successfully and output verified using various samples.

  • EX. NO: 1.c TCP CHAT SERVER / CLIENT

    DATE:

    AIM

    To implement a chat server and client in java using TCP sockets.

    ALGORITHM

    Server

    1. Create a server socket

    2. Wait for client to be connected.

    3. Read Client's message and display it

    4. Get a message from user and send it to client

    5. Repeat steps 3-4 until the client sends "end"

    6. Close all streams

    7. Close the server and client socket

    8. Stop

    Client

    1. Create a client socket and establish connection with the server

    2. Get a message from user and send it to server

    3. Read server's response and display it

    4. Repeat steps 2-3 until chat is terminated with "end" message

    5. Close all input/output streams

    6. Close the client socket

    7. Stop

  • PROGRAM

    // TCP Chat Server--tcpchatserver.java

    import java.io.*;

    import java.net.*;

    class tcpchatserver

    {

    public static void main(String args[])throws Exception

    {

    PrintWriter toClient;

    BufferedReader fromUser, fromClient;

    try

    {

    ServerSocket Srv = new ServerSocket(5555);

    System.out.print("\nServer started\n");

    Socket Clt = Srv.accept();

    System.out.println("Client connected");

    toClient = new PrintWriter(new BufferedWriter(new

    OutputStreamWriter(Clt.getOutputStream())), true);

    fromClient = new BufferedReader(new

    InputStreamReader(Clt.getInputStream()));

    fromUser = new BufferedReader(new

    InputStreamReader(System.in));

    String CltMsg, SrvMsg;

    while(true)

    {

    CltMsg= fromClient.readLine();

    if(CltMsg.equals("end"))

    break;

    else

    {

    System.out.println("\nServer

  • System.out.println(E.getMessage());

    }

    }

    }

    // TCP Chat Server--tcpchatserver.java

    import java.io.*;

    import java.net.*;

    class tcpchatserver

    {

    public static void main(String args[])throws Exception

    {

    PrintWriter toClient;

    BufferedReader fromUser, fromClient;

    try

    {

    ServerSocket Srv = new ServerSocket(5555);

    System.out.print("\nServer started\n");

    Socket Clt = Srv.accept();

    System.out.println("Client connected");

    toClient = new PrintWriter(new BufferedWriter(new

    OutputStreamWriter(Clt.getOutputStream())), true);

    fromClient = new BufferedReader(new

    InputStreamReader(Clt.getInputStream()));

    fromUser = new BufferedReader(new

    InputStreamReader(System.in));

    String CltMsg, SrvMsg;

    while(true)

    {

    CltMsg= fromClient.readLine();

    if(CltMsg.equals("end"))

    break;

    else

    {

    System.out.println("\nServer

  • Srv.close();

    }

    catch (Exception E)

    {

    System.out.println(E.getMessage());

    }

    }

    }

    OUTPUT

    Server Console

    $ javac tcpchatserver.java

    $ java tcpchatserver

    Server started

    Client connected

    Server

  • EX.NO:1. d TCP FILE SERVER/CLIENT

    DATE:

    AIM

    To implement a file server / client in java using TCP sockets.

    ALGORITHM

    Server

    1. Check given directory name for file server. If not given, then assume current directory.

    2. Create a server socket

    3. Wait for client to be connected.

    4. Get filename to be sent from the Client. If filename is invalid then quit.

    5. Get a message from user and send it to client

    6. Open the file and wirte file contents line-by-line onto output stream.

    7. If end-of-file is encountered then close all streams

    8. Close the sockets

    9. Stop

    Client

    1. Create a client socket and establish connection with the server

    2. Get filename from user and send it to server.

    3. Read file contents line-by-line on input stream and display it

    4. When a null is encountered during read, close all streams

    5. Close the client socket

    6. Stop

  • PROGRAM

    // TCP File Server -- FileServer.java

    import java.io.*;

    import java.net.*;

    public class FileServer

    {

    public static void main(String[] args) throws Exception

    {

    File dir;

    ServerSocket ss;

    Socket conn;

    BufferedReader br;

    PrintWriter pw;

    if(args.length == 0)

    dir = new File("./");

    else

    dir = new File(args[0]);

    if(!dir.exists() || !dir.isDirectory())

    {

    System.out.println("Directory does not exist");

    System.exit(-1);

    }

    try

    {

    ss = new ServerSocket(3210);

    conn = ss.accept();

    br = new BufferedReader(new

    InputStreamReader(conn.getInputStream()));

    pw = new PrintWriter(conn.getOutputStream());

    String name = br.readLine().trim();

    File F = new File(dir, name);

    if((!F.exists()) || F.isDirectory())

    pw.println("File does not exists");

    else

    {

    pw.println("\n");

    BufferedReader fin = new BufferedReader(new

    FileReader(F));

    while(true)

    {

    String line = fin.readLine();

    if(line == null)

    break;

    pw.println(line);

  • }

    System.out.println("File Transferred\n");

    }

    pw.flush();

    pw.close();

    }

    catch(Exception e) {

    System.out.println("Error: " + e);

    }

    }

    }

    // TCP File Client -- FileClient.java

    import java.io.*;

    import java.net.*;

    class FileClient

    {

    public static void main(String args[])throws Exception

    {

    try

    {

    Socket Clt;

    if (args.length == 0)

    Clt = new Socket(InetAddress.getLocalHost(),

    3210);

    else

    Clt = new

    Socket(InetAddress.getByName(args[0]),3210);

    PrintWriter OS =new PrintWriter(new

    BufferedWriter(new OutputStreamWriter(Clt.getOutputStream())),

    true);

    BufferedReader IS = new BufferedReader(new

    InputStreamReader(Clt.getInputStream()));

    BufferedReader br = new BufferedReader(new

    InputStreamReader(System.in));

    String CltMsg, SrvMsg;

    System.out.print("\nFilename : ");

    CltMsg = br.readLine();

    OS.println(CltMsg);

    while ((SrvMsg = IS.readLine()) != null)

    System.out.println(SrvMsg);

    }

    catch(Exception E) {

    System.out.println(E.getMessage());

    }

    }

  • }

    OUTPUT

    Server Console

    $ javac FileServer.java

    $ java FileServer

    File Transferred

    Client Console

    $ javac FileClient.java

    $ java FileClient

    Filename : hello.java

    import java.io.*;

    class hello

    {

    public static void main(String args[])

    {

    System.out.println("hello");

    }

    }

    RESULT

    Thus server transmits a file over the network using TCP socket programming

    PRE LAB (10) POST LAB (10) VIVA (10) TOTAL (30) TOT (10)

  • EX.NO: 2.a UDP SOCKETS

    DATE: UDP ECHO SERVER/CLIENT

    AIM

    To implement echo server and client in java using UDP sockets.

    ALGORITHM

    Server

    1. Create a datagram socket

    2. Receive client's message in a datagram packet.

    3. Read Client's message and display it

    4. Convert text from client to upper case and send it back to client

    5. Repeat steps 2-4 until the client has something to send

    6. Close the server socket

    7. Stop

    Client

    1. Create a datagram socket

    2. Get a message from user

    3. Construct a datagram packet and send it to server

    4. Create a datagram packet to receive echoed message

    5. Read server's response and display it

    6. Repeat steps 2-5 until there is some text to send

    7. Close the client socket

    8. Stop

  • PROGRAM

    // UDPEchoServer

    import java.net.*;

    class UDPEchoServer

    {

    public static void main(String args[]) throws Exception

    {

    DatagramSocket SrvSoc = new DatagramSocket(7777);

    byte[] SData = new byte[1024];

    System.out.println("Server Ready\n");

    while (true)

    {

    byte[] RData = new byte[1024];

    DatagramPacket RPack = new DatagramPacket(RData,RData.length);

    SrvSoc.receive(RPack);

    String Text = new String(RPack.getData());

    if (Text.trim().length() > 0)

    {

    System.out.println("From Client

  • if (args.length == 0)

    IPAddr = InetAddress.getLocalHost();

    else

    IPAddr = InetAddress.getByName(args[0]);

    byte[] SData = new byte[1024];

    System.out.println("To quit, press enter without text");

    while (true)

    {

    System.out.print("\nEnter text for Server : ");

    Text = br.readLine();

    SData = Text.getBytes();

    DatagramPacket SPack = new DatagramPacket(SData,SData.length, IPAddr, 7777);

    CliSoc.send(SPack);

    if (Text.trim().length() == 0)

    break;

    byte[] RData = new byte[1024];

    DatagramPacket RPack = new DatagramPacket(RData,RData.length);

    CliSoc.receive(RPack);

    String Echo = new String(RPack.getData()) ;

    Echo = Echo.trim();

    System.out.println("Echo from Server

  • OUTPUT

    Server Console

    $ javac UDPEchoServer.java

    $ java UDPEchoServer

    Server Ready

    From Client

  • EX.NO: 2.b UDP CHAT SERVER/CLIENT

    DATE:

    AIM

    To implement a chat server and client in java using UDP sockets.

    ALGORITHM

    Server

    1. Create two ports, server port and client port

    2. Create a datagram socket and bind it to client port

    3. Create a datagram packet to receive client message

    4. Wait for client's data and accept it.

    5. Read Client's message

    6. Get data from user

    7. Construct a datagram packet and send message through server port

    8. Repeat steps 3-7 until the client has something to send

    9. Close the server socket

    10. Stop

    Client

    1. Create two ports, server port and client port

    2. Create a datagram socket and bind it to server port

    3. Get data from user

    4. Create a datagram packet and send data with server ip address and client port

    5. Create a datagram packet to receive server message

    6. Read server's response and display it

    7. Repeat steps 3-6 until there is some text to send

    8. Close the client socket

    9. Stop

  • PROGRAM

    // udpchatserver

    import java.io.*;

    import java.net.*;

    class udpchatserver

    {

    public static void main(String args[]) throws Exception

    {

    DatagramSocket SrvSoc = new DatagramSocket(5555);

    byte[] SData = new byte[1024];

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    System.out.println("Server Ready");

    while (true)

    {

    byte[] RData = new byte[1024];

    DatagramPacket RPack = new DatagramPacket(RData,RData.length);

    SrvSoc.receive(RPack);

    String Text = new String(RPack.getData());

    if (Text.trim().length() == 0)

    break;

    System.out.println("\nFrom Client

  • InetAddress IPAddr;

    String Text;

    if (args.length == 0)

    IPAddr = InetAddress.getLocalHost();

    else

    IPAddr = InetAddress.getByName(args[0]);

    byte[] SData = new byte[1024];

    System.out.println("Press Enter without text to quit");

    while (true)

    {

    System.out.print("\nEnter text for server : ");

    Text = br.readLine();

    SData = Text.getBytes();

    DatagramPacket SPack = new DatagramPacket(SData,SData.length, IPAddr, 5555);

    CliSoc.send(SPack);

    if (Text.trim().length() == 0)

    break;

    byte[] RData = new byte[1024];

    DatagramPacket RPack = new DatagramPacket(RData,RData.length);

    CliSoc.receive(RPack);

    String Echo = new String(RPack.getData()) ;

    Echo = Echo.trim();

    System.out.println("From Server

  • OUTPUT

    Server Console

    $ javac udpchatserver.java

    $ java udpchatserver

    Server Ready

    From Client

  • EX.NO: 2.c UDP DNS SERVER/CLIENT

    DATE:

    AIM

    To implement a DNS server and client in java using UDP sockets.

    ALGORITHM

    Server

    1. Define an array of hosts and its corresponding IP address in another array

    2. Create a datagram socket

    3. Create a datagram packet to receive client request

    4. Read the domain name from client to be resolved

    5. Lookup the host array for the domain name

    6. If found then retrieve corresponding address

    7. Construct a datagram packet to send response back to the client

    8. Repeat steps 3-7 to resolve further requests from clients

    9. Close the server socket

    10. Stop

    Client

    1. Create a datagram socket

    2. Get domain name from user

    3. Construct a datagram packet to send domain name to the server

    4. Create a datagram packet to receive server message

    5. If it contains IP address then display it, else display "Domain does not exist"

    6. Close the client socket

    7. Stop

  • PROGRAM

    // udpdnsserver.java

    import java.io.*;

    import java.net.*;

    public class udpdnsserver

    {

    private static int indexOf(String[] array, String str)

    {

    str = str.trim();

    for (int i=0; i < array.length; i++)

    {

    if (array[i].equals(str))

    return i;

    }

    return -1;

    }

    public static void main(String arg[])throws IOException

    {

    String[] hosts = {"yahoo.com", "gmail.com",

    "cricinfo.com", "facebook.com"};

    String[] ip = {"68.180.206.184", "209.85.148.19",

    "80.168.92.140", "69.63.189.16"};

    System.out.println("Press Ctrl + C to Quit");

    while (true)

    {

    DatagramSocket serversocket=new DatagramSocket(1362);

    byte[] senddata = new byte[1021];

    byte[] receivedata = new byte[1021];

    DatagramPacket recvpack = new

    DatagramPacket(receivedata, receivedata.length);

    serversocket.receive(recvpack);

    String sen = new String(recvpack.getData());

    InetAddress ipaddress = recvpack.getAddress();

    int port = recvpack.getPort();

    String capsent;

    System.out.println("Request for host " + sen);

    if(indexOf (hosts, sen) != -1)

    capsent = ip[indexOf (hosts, sen)];

    else

    capsent = "Host Not Found";

    senddata = capsent.getBytes();

    DatagramPacket pack = new DatagramPacket(senddata,

    senddata.length,ipaddress,port);

    serversocket.send(pack);

    serversocket.close();

  • }

    }}

    // udpdnsclient

    import java.io.*;

    import java.net.*;

    public class udpdnsclient

    {

    public static void main(String args[])throws IOException

    {

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    DatagramSocket clientsocket = new DatagramSocket();

    InetAddress ipaddress;

    if (args.length == 0)

    ipaddress = InetAddress.getLocalHost();

    else

    ipaddress = InetAddress.getByName(args[0]);

    byte[] senddata = new byte[1024];

    byte[] receivedata = new byte[1024];

    int portaddr = 1362;

    System.out.print("Enter the hostname : ");

    String sentence = br.readLine();

    senddata = sentence.getBytes();

    DatagramPacket pack = new DatagramPacket(senddata,senddata.length, ipaddress,portaddr);

    clientsocket.send(pack);

    DatagramPacket recvpack =new DatagramPacket(receivedata,receivedata.length);

    clientsocket.receive(recvpack);

    String modified = new String(recvpack.getData());

    System.out.println("IP Address: " + modified);

    clientsocket.close();

    }

    }

  • OUTPUT

    Server Console

    $ javac udpdnsserver.java

    $ java udpdnsserver

    Press Ctrl + C to Quit

    Request for host yahoo.com

    Request for host cricinfo.com

    Request for host youtube.com

    Client Console

    $ javac udpdnsclient.java

    $ java udpdnsclient

    Enter the hostname : yahoo.com

    IP Address: 68.180.206.184

    $ java udpdnsclient

    Enter the hostname : cricinfo.com

    IP Address: 80.168.92.140

    $ java udpdnsclient

    Enter the hostname : youtube.com

    IP Address: Host Not Found

    RESULT

    Thus domain name requests by the client are resolved into their respective logical address

    using lookup method.

    PRE LAB (10) POST LAB (10) VIVA (10) TOTAL (30) TOT (10)

  • RAW SOCKETS

    EX.NO: 3 PACKET CAPTURE

    AIM

    To sniff and parse packets that pass through using raw sockets.

    ALGORITHM

    1. Set the ethernet interface in promiscuous mode to sniff all packets

    2. Create a raw socket with Ethernet-to-IP protocol.

    3. Bind socket to the Ethernet interface using bind()

    4. Get the number of packets to be sniffed from the user.

    5. When a proper packet arrives, receive it using recvfrom()

    6. Print the entire packet contents in hexadecimal using a loop.

    7. Parse the packet

    a. Print source and destination MAC addresss from Ethernet header

    b. Print source and destination IP address from IP header

    c. If the transport layer protocol is TCP, then print the source and destination port from TCP

    header

    d. If the packet contains data then print the data

    8. Repeat steps 57 until required number of packets are sniffed

    9. Stop

    PROGRAM

    //Packet Sniffing sniffdata.c

    #include

    #include

    #include

    #include

    #include

    #include

    #include

    #include

    #include

    #include

    #include

    #include

    #include

    int CreateRawSocket(int protocol_to_sniff)

    {

    int rawsock;

    if((rawsock = socket(PF_PACKET, SOCK_RAW,htons(protocol_to_sniff)))== -1)

    {

    perror("Error creating raw socket: ");

    exit(-1);

    }

    return rawsock;

  • }

    int BindRawSocketToInterface(char *device, int rawsock, int protocol)

    {

    struct sockaddr_ll sll;

    struct ifreq ifr;

    bzero(&sll, sizeof(sll));

    bzero(&ifr, sizeof(ifr));

    /* Get Interface Index */

    strncpy((char *)ifr.ifr_name, device, IFNAMSIZ);

    if((ioctl(rawsock, SIOCGIFINDEX, &ifr)) == -1)

    {

    printf("Error getting Interface index !\n");

    exit(-1);

    }

    /* Bind raw socket to this interface */

    sll.sll_family = AF_PACKET;

    sll.sll_ifindex = ifr.ifr_ifindex;

    sll.sll_protocol = htons(protocol);

    if((bind(rawsock, (struct sockaddr *)&sll, sizeof(sll)))== -1)

    {

    perror("Error binding raw socket to interface\n");

    exit(-1);

    }

    return 1;

    }

    void PrintPacketInHex(unsigned char *packet, int len)

    {

    unsigned char *p = packet;

    printf("\n\n---------Packet---Starts----\n\n");

    while(len--)

    {

    printf("%.2x ", *p);

    p++;

    }

    printf("\n\n--------Packet---Ends-----\n\n");

    }

    PrintInHex(char *mesg, unsigned char *p, int len)

    {

    printf(mesg);

    while(len--)

    {

    printf("%.2X ", *p);

    p++;

    }

    }

    ParseEthernetHeader(unsigned char *packet, int len)

  • {

    struct ethhdr *ethernet_header;

    if(len > sizeof(struct ethhdr))

    {

    ethernet_header = (struct ethhdr *)packet;

    /* First set of 6 bytes are Destination MAC */

    PrintInHex("Destination MAC: ",ethernet_header->h_dest,6);

    printf("\n");

    /* Second set of 6 bytes are Source MAC */

    PrintInHex("Source MAC: ",ethernet_header->h_source,6);

    printf("\n");

    /* Last 2 bytes in Ethernet header is the protocol */

    PrintInHex("Protocol: ",(void *)

    &ethernet_header->h_proto, 2);

    printf("\n");

    }

    else

    {

    printf("Packet size too small !\n");

    }

    }

    ParseIpHeader(unsigned char *packet, int len)

    {

    struct ethhdr *ethernet_header;

    struct iphdr *ip_header;

    /*Check if packet contains IP header using Ethernet header*/

    ethernet_header = (struct ethhdr *)packet;

    if(ntohs(ethernet_header->h_proto) == ETH_P_IP)

    {

    /* The IP header is after the Ethernet header */

    if(len >= (sizeof(struct ethhdr)+sizeof(struct iphdr)))

    {

    ip_header=(struct iphdr*)(packet+sizeof(struct ethhdr));

    /* print the Source and Destination IP address */

    printf("Dest IP address: %s\n",

    inet_ntoa(ip_header->daddr));

    printf("Source IP address: %s\n",

    inet_ntoa(ip_header->saddr));

    }

    else

    {

    printf("IP packet does not have full header\n");

    }

    }

    }

    ParseTcpHeader(unsigned char *packet , int len)

  • {

    struct ethhdr *ethernet_header;

    struct iphdr *ip_header;

    struct tcphdr *tcp_header;

    /* Check if enough bytes are there for TCP Header */

    if(len >= (sizeof(struct ethhdr) + sizeof(struct iphdr) +

    sizeof(struct tcphdr)))

    {

    /* Do the checks: Is it an IP pkt and is it TCP ? */

    ethernet_header = (struct ethhdr *)packet;

    if(ntohs(ethernet_header->h_proto) == ETH_P_IP)

    {

    ip_header = (struct iphdr *)(packet +

    sizeof(struct ethhdr));

    if(ip_header->protocol == IPPROTO_TCP)

    {

    tcp_header = (struct tcphdr*)(packet +

    sizeof(struct ethhdr) + ip_header->ihl*4 );

    /* Print the Dest and Src ports */

    printf("Source Port:%d\n",ntohs(tcp_header->source));

    printf("Dest Port: %d\n", ntohs(tcp_header->dest));

    }

    else

    {

    printf("Not a TCP packet\n");

    }

    }

    else

    {

    printf("Not an IP packet\n");

    }

    }

    else

    {

    printf("TCP Header not present \n");

    }

    }

    int ParseData(unsigned char *packet, int len)

    {

    struct ethhdr *ethernet_header;

    struct iphdr *ip_header;

    struct tcphdr *tcp_header;

    unsigned char *data;

    int data_len;

    /* Check if any data is there */

    if(len > (sizeof(struct ethhdr) + sizeof(struct iphdr) + sizeof(struct tcphdr)))

  • {

    ip_header = (struct iphdr*)(packet +

    sizeof(struct ethhdr));

    data = (packet + sizeof(struct ethhdr) +

    ip_header->ihl*4 +sizeof(struct tcphdr));

    data_len = ntohs(ip_header->tot_len) - ip_header->ihl*4- sizeof(struct tcphdr);

    if(data_len)

    {

    printf("Data Len : %d\n", data_len);

    PrintInHex("Data : ", data, data_len);

    printf("\n\n");

    return 1;

    }

    else

    {

    printf("No Data in packet\n");

    return 0;

    }

    }

    else

    {

    printf("No Data in packet\n");

    return 0;

    }

    }

    int IsIpAndTcpPacket(unsigned char *packet, int len)

    {

    struct ethhdr *ethernet_header;

    struct iphdr *ip_header;

    ethernet_header = (struct ethhdr *)packet;

    if(ntohs(ethernet_header->h_proto) == ETH_P_IP)

    {

    ip_header = (struct iphdr *)(packet +

    sizeof(struct ethhdr));

    if(ip_header->protocol == IPPROTO_TCP)

    return 1;

    else

    return -1;

    }

    else

    return -1;

    }

    main(int argc, char **argv)

    {

    int raw;

    unsigned char packet_buffer[2048];

  • int len;

    int packets_to_sniff;

    struct sockaddr_ll packet_info;

    int packet_info_size = sizeof(packet_info);

    /* create the raw socket */

    raw = CreateRawSocket(ETH_P_IP);

    /* Bind socket to interface */

    BindRawSocketToInterface(argv[1], raw, ETH_P_IP);

    /* Get number of packets to sniff from user */

    packets_to_sniff = atoi(argv[2]);

    /* Start Sniffing and print Hex of every packet */

    while(packets_to_sniff--)

    {

    if((len = recvfrom(raw, packet_buffer, 2048, 0,

    (struct sockaddr*)&packet_info, &packet_info_size))== -1)

    {

    perror("Recv from returned -1: ");

    exit(-1);

    }

    else

    {

    /* Packet has been received successfully !! */

    PrintPacketInHex(packet_buffer, len);

    /* Parse Ethernet Header */

    ParseEthernetHeader(packet_buffer, len);

    /* Parse IP Header */

    ParseIpHeader(packet_buffer, len);

    /* Parse TCP Header */

    ParseTcpHeader(packet_buffer, len);

    if(IsIpAndTcpPacket(packet_buffer, len))

    {

    if(!ParseData(packet_buffer, len))

    packets_to_sniff++;

    }

    }

    }

    return 0;

    }

    OUTPUT

    $su

    Password:

    # gcc sniffdata.c -o sniffdata

    # ifconfig eth0 promisc

    # ./sniffdata eth0 1

  • ---------Packet---Starts----

    01 00 5e 7f ff fa 18 f4 6a 16 a2 a2 08 00 45 00 01 ff 2a ec 00

    00 01 11 ec 11 ac 10 04 e6 ef ff ff fa 07 6c 07 6c 01 eb 65 d1

    4e 4f 54 49 46 59 20 2a 20 48 54 54 50 2f 31 2e 31 0d 0a 48 6f

    73 74 3a 32 33 39 2e 32 35 35 2e 32 35 35 2e 32 35 30 3a 31 39

    30 30 0d 0a 4e 54 3a 75 72 6e 3a 64 6d 63 2d 73 61 6d 73 75 6e

    67 2d 63 6f 6d 3a 64 65 76 69 63 65 3a 53 79 6e 63 53 65 72 76

    65 72 3a 31 0d 0a 4e 54 53 3a 73 73 64 70 3a 61 6c 69 76 65 0d

    0a 4c 6f 63 61 74 69 6f 6e 3a 68 74 74 70 3a 2f 2f 31 37 32 2e

    31 36 2e 34 2e 32 33 30 3a 32 38 36 39 2f 75 70 6e 70 68 6f 73

    74 2f 75 64 68 69 73 61 70 69 2e 64 6c 6c 3f 63 6f 6e 74 65 6e

    --------Packet---Ends-----

    Destination MAC: 01 00 5E 7F FF FA

    Source MAC: 18 F4 6A 16 A2 A2

    Protocol: 08 00

    Dest IP address: 239.255.255.250

    Source IP address: 172.16.4.230

    Not a TCP packet

    Data Len : 471

    Data : 50 2F 31 2E 31 0D 0A 48 6F 73 74 3A 32 33 39 2E 32 35

    35 2E 32 35 35 2E 32 35 30 3A 31 39 30 30 0D 0A 4E 54 3A 75 72

    6E 3A 64 6D 63 2D 73 61 6D 73 75 6E 67 2D 63 6F 6D 3A 64 65 76

    69 63 65 3A 53 79 6E 63 53 65 72 76 65 72 3A 31 0D 0A 4E 54 53

    3A 73 73 64 70 3A 61 6C 69 76 65 0D 0A 4C 6F 63 61 74 69 6F 6E

    3A 68 74 74 70 3A 2F 2F 31 37 32 2E 31 36 2E 34 2E 32 33 30 3A

    32 38 36 39 2F 75 70 6E 70 68 6F 73 74 2F 75 64 68 69 73 61 70

    69 2E 64 6C 6C 3F 63 6F 6E 74 65 6E

    RESULT

    Thus packets that pass through the host were sniffed. The Ethernet, IP and TCP headers

    along with data contents were parsed.

    PRE LAB (10) POST LAB (10) VIVA (10) TOTAL (30) TOT (10)

  • EX.NO: 4.a REMOTE PROCEDURE CALL

    DATE: ARITHMETIC CALCULATOR USING RPC-RMI

    AIM

    To implement simple calculator and invoke arithmetic operations from a remote client.

    ALGORITHM

    Interface

    1. Declare server's remote interface for simple arithmetic operations such as addition,

    subtraction, multiplication, division, etc.

    Implementation

    1. Define arithmetic operation modules for all interfaces.

    2. Create a calc object.

    3. Register the calc object with RMI registry using rebind method.

    Client

    1. Obtain operands from the user.

    2. Check for rmi calc service availability using lookup method.

    3. Call arithmetic operations on the remote server.

    4. Display results.

    Procedure

    1. Compile the three java files (Interface, Implementation and Client).

    2. Generate stub by compiling the implementation file using RMI compiler (rmic).

    3. Distribute the class files of Client, Interface and Stub to the clients.

    4. Start the RMI registry on the server.

    5. Start the server (implementation file).

    6. Run the client program.

  • PROGRAM

    // RMI Calc interface -- CalcInf.java

    import java.rmi.*;

    public interface CalcInf extends Remote

    {

    public long add(int a, int b) throws RemoteException;

    public int sub(int a, int b) throws RemoteException;

    public long mul(int a, int b) throws RemoteException;

    public int div(int a, int b) throws RemoteException;

    public int rem(int a, int b) throws RemoteException;

    }

    // RMI Calc Implementation -- CalcImpl.java

    import java.rmi.*;

    import java.rmi.server.*;

    public class CalcImpl extends UnicastRemoteObject implements CalcInf

    {

    public CalcImpl() throws RemoteException { }

    public long add(int a, int b) throws RemoteException

    {

    return a + b;

    }

    public int sub(int a, int b) throws RemoteException

    {

    int c = a > b ? a - b : b - a;

    return c;

    }

    public long mul(int a, int b) throws RemoteException

    {

    return a * b;

    }

    public int div(int a, int b) throws RemoteException

    {

    return a / b;

    }

    public int rem(int a, int b) throws RemoteException

    {

    return a % b;

    }

    public static void main(String args[])

    {

    try

    {

    calcinf C = new calcimpl();

    Naming.rebind("Calc1234", C);

    }

  • catch (Exception e)

    {

    System.out.println(e);

    }

    }

    }

    // RMI Calc Client -- CalcClient.java

    import java.rmi.*;

    import java.net.*;

    public class CalcClient

    {

    public static void main(String[] args) throws Exception

    {

    try {

    CalcInf C = (CalcInf)

    Naming.lookup("rmi://localhost/Calc1234");

    int a, b;

    if (args.length != 2)

    {

    System.out.println("Usage: java CalcClient ");

    System.exit(-1);

    }

    a = Integer.parseInt(args[0]);

    b = Integer.parseInt(args[1]);

    System.out.println( "\nBasic Remote Calc\n" );

    System.out.println("Summation : " + C.add(a, b));

    System.out.println("Difference : " + C.sub(a, b));

    System.out.println("Product : " + C.mul(a, b));

    System.out.println("Quotient : " + C.div(a, b));

    System.out.println("Remainder : " + C.rem(a, b));

    }

    catch (Exception E) {

    System.out.println(E.getMessage());

    }

    }

    }

  • OUTPUT

    Server

    $ javac CalcInf.java

    $ javac CalcImpl.java

    $ javac CalcClient.java

    $ rmic CalcImpl

    $ mkdir clnt

    $ cp CalcInf.class CalcClient.class CalcImpl_Stub.class ./clnt

    $ rmiregistry&

    $ java CalcImpl

    Client

    $ cd clnt

    $ java CalcClient 6 8

    Basic Remote Calc

    Summation : 14

    Difference : 2

    Product : 48

    Quotient : 0

    Remainder : 6

    RESULT

    Thus remote procedure calls for basic operations of a calculator is executed using Java

    RMI.

  • EX.NO: 4.b SORTING

    DATE:

    AIM

    To implement bubble sort and sort data using a remote client.

    ALGORITHM

    Interface

    1. Declare server's remote interface for bubble sort.

    Implementation

    1. Define bubble sort procedure.

    2. Create a sort object.

    3. Register the sort object with RMI registry using rebind method.

    Client

    1. Obtain unsorted data from the user.

    2. Check for rmi sort service availability using lookup method.

    3. Call sort method on the remote server.

    4. Display the sorted array.

    Procedure

    1. Compile the three java files (Interface, Implementation and Client).

    2. Generate stub by compiling the implementation file using RMI compiler (rmic).

    3. Distribute the class files of Client, Interface and Stub to the clients.

    4. Start the RMI registry on the server.

    5. Start the server (implementation file).

    6. Run the client program.

  • PROGRAM

    // RMI Sort interface -- sortinf.java

    import java.rmi.*;

    public interface sortinf extends Remote

    {

    public int[] sort(int a[], int n) throws RemoteException;

    }

    //RMI Sort Implementation -- sortimpl.java

    import java.rmi.*;

    import java.rmi.server.*;

    public class sortimpl extends UnicastRemoteObject implements sortinf

    {

    public sortimpl() throws RemoteException { }

    public int[] sort(int a[], int n) throws RemoteException

    {

    int i,j,t;

    for(i=0; i

  • // RMI Sort Client -- sortclient.java

    import java.rmi.*;

    import java.net.*;

    public class sortclient

    {

    public static void main(String[] args) throws Exception

    {

    try

    {

    sortinf S = (sortinf)

    Naming.lookup("rmi://localhost/Sort1234");

    int i;

    int n = args.length;

    int a[] = new int[n];

    int b[] = new int[n];

    for(i=0; i

  • OUTPUT

    Server

    $ javac sortinf.java

    $ javac sortimpl.java

    $ javac sortclient.java

    $ rmic sortimpl

    $ mkdir clnt

    $ cp sortinf.class sortclient.class sortimpl_Stub.class ./clnt

    $ rmiregistry&

    $ java sortimpl

    Client

    $ cd clnt

    $ java sortclient 8 4 0 3 -2 5 1 6

    Sorted array : -2 0 1 3 4 5 6 8

    RESULT

    Thus remote procedure calls is made to sort a random data set using Java RMI.

  • EX.NO: 4.c STRING REVERSE

    DATE:

    AIM

    To implement string manipulations on a remote host and perform string operations.

    ALGORITHM

    Interface

    1. Declare server's remote interface for string reverse.

    Implementation

    1. Define string reverse using string buffer class methods.

    2. Create a stringfn object.

    3. Register the stringfn object with RMI registry using rebind method.

    Client

    1. Obtain text from the user.

    2. Check for rmi stringfn service availability using lookup method.

    3. Call string operations on the remote server.

    4. Display results.

    Procedure

    1. Compile the three java files (Interface, Implementation and Client).

    2. Generate stub by compiling the implementation file using RMI compiler (rmic).

    3. Distribute the class files of Client, Interface and Stub to the clients.

    4. Start the RMI registry on the server.

    5. Start the server (implementation file).

    6. Run the client program.

  • PROGRAM

    // RMI string interface -- strinf.java

    import java.rmi.*;

    public interface strinf extends Remote

    {

    public String strfn(String s) throws RemoteException;

    }

    // RMI string implementation -- strimpl.java

    import java.rmi.*;

    import java.rmi.server.*;

    public class strimpl extends UnicastRemoteObject implements

    strinf {

    public strimpl() throws RemoteException { }

    public String strfn(String s) throws RemoteException

    {

    StringBuffer s1 = new StringBuffer(s);

    s1.reverse();

    return (s1.toString()); //String Revers

    /* return (s.toUpperCase()); */ // Lower-to-Upper Case

    /* return s; */ // Remote Echo server

    }

    public static void main(String arg[])

    {

    try

    {

    strinf si = new strimpl();

    Naming.rebind("Str1234", si);

    }

    catch(Exception e)

    {

    System.out.println(e);

    }

    }

    }

    // RMI String Client -- strclient.java

    import java.rmi.*;

    import java.net.*;

    public class strclient

    {

    public static void main(String[] args) throws Exception

    {

    try

    {

    strinf S = (strinf)

  • Naming.lookup("rmi://localhost/Str1234");

    if (args.length != 1)

    {

    System.out.println( "Usage: java strclient

    ");

    System.exit(-1);

    }

    System.out.println( "Output String : " +

    S.strfn(args[0]));

    }

    catch (Exception E)

    {

    System.out.println(E.getMessage());

    }

    }

    }

  • OUTPUT

    Server

    $ javac strinf.java

    $ javac strimpl.java

    $ javac strclient.java

    $ rmic strimpl

    $ mkdir clnt

    $ cp strinf.class strclient.class strimpl_Stub.class ./clnt

    $ rmiregistry&

    $ java strimpl

    Client

    $ cd clnt

    $ java strclient SMKFIT

    Output String : TIFKMS

    RESULT

    Thus remote procedure calls for string manipulation is executed using Java RMI.

    PRE LAB (10) POST LAB (10) VIVA (10) TOTAL (30) TOT (10)

  • PROTOCOL SIMULATION

    EX.NO: 5.a GO BACK N ARQ

    DATE:

    AIM

    To simulate a sliding window protocol that uses Go Back N ARQ.

    ALGORITHM

    Sender

    1. Create a server socket

    2. Assume the sending window size as 7 (m = 3).

    3. If receiver is ready, initialize sender's frame sequence to 0.

    4. Get data from user.

    5. Send it to the receiver along with sequence number.

    6. Increment sequence number by 1.

    7. Repeat steps 46 until all frames have been sent.

    8. Wait for acknowledgements.

    9. If all acknowledgements have arrived then go to step 12.

    10. Set sequence number to earliest outstanding frame for which there is no ACK.

    11. Go to step 4.

    12. Stop

    Receiver

    1. Indicate to sender, the readiness to accept frames.

    2. Initialize receiver's expected frame sequence to 0.

    3. Accept the incoming frame.

    4. If frame's sequence receiver's sequence then go to step 7.

    5. Send an acknowledgement.

    6. Repeat steps 36 until all frames are received in sequence and go to step 9

    7. Discard frame, thereby force the sender to retransmit.

    8. Go to step 3.

    9. Stop

  • PROGRAM

    // Go Back N Sender--GBNSend.java

    import java.io.*;

    import java.net.*;

    public class GBNSend

    {

    String output[] = new String[7];

    void sendMsg(BufferedReader buff, BufferedReader in,PrintWriter out, int x) throws Exception

    {

    try

    {

    for(int i=x; i

  • else

    {

    System.out.println("Frame" + j + " lost/corrupt.Go Back & resend");

    x = j;

    g.sendMsg(buff,in,out,j);

    --j;

    }

    }

    soc.close();

    ssoc.close();

    }

    }

    //Go Back N Receiver--GBNReceive.java

    import java.io.*;

    import java.net.*;

    public class GBNReceive

    {

    String input[] = new String[7];

    void ReceiveMsg(BufferedReader buff, PrintWriter out,

    int x) throws Exception

    {

    try

    {

    for(int i=x; i

  • if(g.input[j].startsWith(s))

    {

    String rmsg = g.input[j];

    rmsg = rmsg.substring(1,rmsg.length());

    System.out.println("Frame" + j + "data is " + rmsg);

    out.println(j + "ack");

    out.flush();

    }

    else

    {

    out.println("no ack");

    out.flush();

    x = j;

    g.ReceiveMsg(buff,out,j);

    --j;

    }

    }

    soc.close();

    }

    }

    OUTPUT

    Sender

    $ javac GBNSend.java

    $ java GBNSend

    Window size 7

    Enter message in format--SeqNoData

    Content for frame0 : 0hi

    Content for frame1 : 1hello

    Content for frame2 : 2i am here

    Content for frame3 : 3where r u?

    Content for frame4 : here only

    Content for frame5 : 5can u see me

    Content for frame6 : 6which direction

    Ack for frame0

    Ack for frame1

    Ack for frame2

    Ack for frame3

    Frame4 lost/corrupt. Go Back & resend

    Content for frame4 : 4here only

    Content for frame5 : 5which direction

    Content for frame6 : ok

    Ack for frame4

    Ack for frame5

  • Frame6 lost/corrupt. Go Back & resend

    Content for frame6 : 6South

    Ack for frame6

    Receiver

    $ javac GBNReceive.java

    $ java GBNReceive

    Frame0 data is hi

    Frame1 data is hello

    Frame2 data is i am here

    Frame3 data is where r u?

    Frame4 data is here only

    Frame5 data is which direction

    Frame6 data is South

    RESULT

    Thus using Go Back N procedure, the sender retransmits all frames from the earliest

    outstanding frame.

  • EX.NO: 5.b SELECTIVE REPEAT ARQ

    DATE:

    AIM

    To simulate a sliding window protocol that uses Selective Repeat ARQ.

    ALGORITHM

    Sender

    1. Create a server socket

    2. Assume sending window size as 7.

    3. If receiver is ready, initialize sender's frame sequence to 0.

    4. Get data from user.

    5. Send it to receiver along with sequence number.

    6. Increment sequence number by 1.

    7. Repeat steps 46 until all frames have been sent.

    8. Wait for acknowledgements.

    9. If all acknowledgements have arrived then go to step 12

    10. Resend the earliest outstanding frame for which there is no ACK.

    11. Go to step 8.

    12. Stop

    Receiver

    1. Indicate to the sender, the readiness to accept frames.

    2. Initialize receiver's expected frame sequence to 0.

    3. Accept the incoming frame.

    4. If frame is corrupt then step 8.

    5. If frames are in order then step 6 else step 3.

    6. Send acknowledgements.

    7. If ACK for all frames are sent then go to step 10

    8. Discard the frame, thereby force the sender to retransmit

    9. Go to step 3

    10. Stop

  • PROGRAM

    // Selective Repeat Sender--SRSend.java

    import java.io.*;

    import java.net.*;

    public class SRSend

    {

    String output[] = new String[7];

    void sendMsg(BufferedReader buff, BufferedReader in,PrintWriter out, int x, int flag) throws

    Exception

    {

    try

    {

    if(flag == 1)

    {

    for(int i=0; i

  • int x = 0;

    g.sendMsg(buff,in,out,0,1);

    for(int j=x; j

  • Socket soc = new Socket("localhost", 6000);

    BufferedReader buff = new BufferedReader(new InputStreamReader(soc.getInputStream()));

    PrintWriter out = new PrintWriter(new

    OutputStreamWriter(soc.getOutputStream()));

    int x=0;

    g.ReceiveMsg(buff,out,0,1);

    for(int j=x; j

  • OUTPUT

    Sender

    $ javac SRSend.java

    $ java SRSend

    Window size 7

    Window size 7

    Enter message in format--SeqNoData

    Content for frame0 : 0hi

    Content for frame1 : 1hello

    Content for frame2 : 2i am here

    Content for frame3 : 3where r u?

    Content for frame4 : here only

    Content for frame5 : 5can u see me

    Content for frame6 : 6which direction

    Ack for frame0

    Ack for frame1

    Ack for frame2

    Ack for frame3

    Frame4 lost/corrupt. Resend it

    Content for frame4 : 4here only

    Ack for frame4

    Ack for frame5

    Ack for frame6

    Receiver

    $ javac SRReceive.java

    $ java SRReceive

    Frame0 data is hi

    Frame1 data is hello

    Frame2 data is i am here

    Frame3 data is where r u?

    Frame4 data is here only

    Frame5 data is can u see me

    Frame6 data is which direction

    RESULT

    Thus using Selective Repeat procedure, the sender retransmits only frames that are

    unacknowledged.

  • EX.NO: 5.c ARP SERVER/CLIENT

    DATE:

    AIM

    To know the physical address of a host when its logical address is known using ARP

    protocol.

    ALGORITHM

    Target/Server

    1. Create a server socket.

    2. Accept client connection.

    3. Read IP address from the client request

    4. Check its configuration file and compare with its logical address.

    5. If there is a match, send the host physical address.

    6. Stop

    Client

    1. Create a socket.

    2. Send IP address to the target machine

    3. Receive target's response

    4. If it is a MAC address then display it and go to step 6

    5. Display "Host not found"

    6. Stop

  • PROGRAM

    //ARP Server -- arpserver.java

    import java.io.*;

    import java.net.*;

    class arpserver

    {

    public static void main(String args[])throws IOException

    {

    try

    {

    ServerSocket soc = new ServerSocket(2500);

    System.out.println("Server started");

    Socket client = null;

    client = soc.accept();

    String str;

    PrintStream ps = new PrintStream(client.getOutputStream());

    BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));

    Runtime r = Runtime.getRuntime();

    Process p = r.exec("ifconfig eth0");

    BufferedReader pin=new BufferedReader(new InputStreamReader(p.getInputStream()));

    String haddr = "";

    String ipaddr = br.readLine();

    int flag = 0;

    while((str = pin.readLine())!=null)

    {

    System.out.println(str);

    if((str.indexOf("HWaddr")) != -1)

    {

    int tlen = str.length();

    int hlen = tlen - 19;

    haddr = str.substring(hlen,tlen);

    }

    else if ((str.indexOf(ipaddr)) != -1)

    {

    flag = 1;

    }

    }

    if (flag == 1)

    ps.println(haddr);

    ps.close();

    br.close();

    pin.close();

    client.close();

    soc.close();

    }

  • catch(IOException io)

    {

    System.err.println("Exception : " + io.toString());

    }

    }

    }

    //ARP Client -- arpclient.java

    import java.io.*;

    import java.net.*;

    class arpclient

    {

    public static void main(String args[])

    {

    try

    {

    Socket client = new Socket("localhost", 2500);

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    PrintStream ps = new PrintStream(client.getOutputStream());

    String ipaddr,haddr = null;

    BufferedReader sin = new BufferedReader(new InputStreamReader(client.getInputStream()));

    System.out.print("Enter the IP address : ");

    ipaddr = br.readLine();

    ps.println(ipaddr);

    haddr = sin.readLine();

    if (haddr == null)

    System.out.println("Host does not exist");

    else

    System.out.println("Physical Address " + haddr);

    ps.close();

    br.close();

    client.close();

    }

    catch(IOException io)

    {

    System.err.println(io.toString());

    }

    }

    }

  • OUTPUT

    Server

    $ javac arpserver.java

    $ java arpserver

    Server started

    eth0 Link encap:Ethernet HWaddr B8:AC:6F:1B:AB:06

    inet addr:172.16.12.251 Bcast:172.255.255.255 Mask:255.0.0.0

    inet6 addr: fe80::baac:6fff:fe1b:ab06/64 Scope:Link

    UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1

    RX packets:450 errors:0 dropped:0 overruns:0 frame:0

    TX packets:127 errors:0 dropped:0 overruns:0 carrier:0

    collisions:0 txqueuelen:1000

    RX bytes:48118 (46.9 KiB) TX bytes:21025 (20.5 KiB)

    Interrupt:16

    Client

    $ javac arpclient.java

    $ java arpclient

    Enter the IP address : 172.16.12.251

    Physical Address B8:AC:6F:1B:AB:06

    RESULT

    Thus using Address Rresolution Protoocl, a hosts MAC address is obtained.

  • EX.NO: 5.d RARP CLIENT/SERVER

    DATE:

    AIM

    To know the logical address of a host when its physical address is known using RARP

    protocol.

    ALGORITHM

    Target/Server

    1. Create a server socket.

    2. Accept client connection.

    3. Read MAC address from the client request

    4. Check its configuration file and compare with its physical address.

    5. If there is a match, send the host logical address.

    6. Stop

    Client

    1. Create a socket.

    2. Send physical address to the target machine

    3. Receive target's response

    4. If it is a IP address then display it and go to step 6

    5. Display "Host not found"

    6. Stop

  • PROGRAM

    //RARP Server -- rarpserver.java

    import java.io.*;

    import java.net.*;

    class rarpserver

    {

    public static void main(String args[])throws IOException

    {

    try

    {

    ServerSocket soc = new ServerSocket(2500);

    System.out.println("Server started");

    Socket client = null;

    client = soc.accept();

    String str;

    PrintStream ps = new PrintStream(client.getOutputStream());

    BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));

    Runtime r = Runtime.getRuntime();

    Process p = r.exec("ifconfig eth0");

    BufferedReader pin = new BufferedReader(new InputStreamReader(p.getInputStream()));

    String ipaddr = "";

    String haddr = br.readLine();

    int flag = 0;

    while((str = pin.readLine())!=null)

    {

    System.out.println(str);

    if ((str.indexOf(haddr)) != -1)

    {

    flag = 1;

    }

    else if((str.indexOf("inet addr")) != -1)

    {

    int pos = str.indexOf("inet addr:") + 10;

    int offset = pos + 13;

    ipaddr = str.substring(pos,offset);

    }

    }

    if (flag == 1)

    ps.println(ipaddr);

    ps.close();

    br.close();

    pin.close();

    client.close();

    soc.close();

    }

  • catch(IOException io)

    {

    System.err.println("Exception : " + io.toString());

    }

    }

    }

    // RARP Client -- rarpclient.java

    import java.io.*;

    import java.net.*;

    class rarpclient

    {

    public static void main(String args[])

    {

    try

    {

    Socket client = new Socket("localhost", 2500);

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    PrintStream ps = new

    PrintStream(client.getOutputStream());

    String haddr,ipaddr = null;

    BufferedReader sin = new BufferedReader(new InputStreamReader(client.getInputStream()));

    System.out.print("Enter the physical address : ");

    haddr = br.readLine();

    ps.println(haddr);

    ipaddr = sin.readLine();

    if (ipaddr == null)

    System.out.println("Host does not exist");

    else

    System.out.println("Logical Address " + ipaddr);

    ps.close();

    br.close();

    client.close();

    }

    catch(IOException io)

    {

    System.err.println(io.toString());

    }

    }

    }

  • OUTPUT

    Server

    $ javac rarpserver.java

    $ java rarpserver

    Server started

    eth0 Link encap:Ethernet HWaddr B8:AC:6F:1B:AB:06

    inet addr:172.16.12.251 Bcast:172.255.255.255 Mask:255.0.0.0

    inet6 addr: fe80::baac:6fff:fe1b:ab06/64 Scope:Link

    UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1

    RX packets:450 errors:0 dropped:0 overruns:0 frame:0

    TX packets:127 errors:0 dropped:0 overruns:0 carrier:0

    collisions:0 txqueuelen:1000

    RX bytes:48118 (46.9 KiB) TX bytes:21025 (20.5 KiB)

    Interrupt:16

    Client

    $ javac rarpclient.java

    $ java rarpclient

    Enter the physical address : B8:AC:6F:1B:AB:06

    Logical Address 172.16.12.251

    RESULT

    Thus using Reverse ARP protocol, IP address of a host is obtained.

    PRE LAB (10) POST LAB (10) VIVA (10) TOTAL (30) TOT (10)

  • EX.NO: 6.a EXPERIMENTS USING SIMULATORS

    DATE: USER DATAGRAM PROTOCOL USING NS-2

    AIM:

    To implement User Datagram Protocol (UDP) using NS-2

    ALGORITHM:

    Step 1: Start network simulator OTCL editor.

    Step 2: Create new simulator using set ns [new Simulator] syntax

    Step 3: Create procedure to trace all path

    proc finish {} {

    global ns nf tf

    $ns flush-trace

    close $nf

    close $tf

    exec nam udp.nam &

    exit 0 }

    Step 4: Connect with TCP and SINK command.

    $ns connect $tcp $sink

    Step 5: Run and Execute the program.

    $ns run

  • PROGRAM:

    set ns [new Simulator]

    set nf [open udp.nam w]

    $ns namtrace-all $nf

    set tf [open out.tr w]

    $ns trace-all $tf

    proc finish {} {

    global ns nf tf

    $ns flush-trace

    close $nf

    close $tf

    exec nam udp.nam &

    exit 0

    }

    set n0 [$ns node]

    set n1 [$ns node]

    set n2 [$ns node]

    set n3 [$ns node]

    set n4 [$ns node]

    set n5 [$ns node]

    $ns duplex-link $n0 $n4 1Mb 50ms DropTail

    $ns duplex-link $n1 $n4 1Mb 50ms DropTail

    $ns duplex-link $n2 $n5 0.1Mb 1ms DropTail

    $ns duplex-link $n3 $n5 1Mb 1ms DropTail

    $ns duplex-link $n4 $n5 1Mb 50ms DropTail

    $ns duplex-link-op $n2 $n5 queuePos 1

    set tcp [new Agent/UDP]

    $ns attach-agent $n0 $tcp

    set sink [new Agent/Null]

    $ns attach-agent $n2 $sink

    $ns connect $tcp $sink

    set ftp [new Application/Traffic/CBR]

    $ftp attach-agent $tcp

    $ns at 0.0 "$ftp start"

    $ns at 2.5 "$ftp stop"

    $ns at 3 "finish"

    $ns run

  • OUTPUT:

    RESULT:

    Thus the program for implementing UDP was executed using NS-2 and output verified

    using Network Animator.

  • EX.NO: 6.b TRANSMISSION CONTROL PROTOCOL USING NS-2

    DATE:

    AIM:

    To implement Transmission Control Protocol (TCP) using NS-2

    ALGORITHM:

    Step 1: Start network simulator OTCL editor.

    Step 2: Create new simulator using set ns [new Simulator] syntax

    Step 3: Create procedure to trace all path

    proc finish {} {

    global ns nf tf

    $ns flush-trace

    close $nf

    close $tf

    exec nam tcp.nam &

    exit 0}

    Step 4: Connect with TCP and SINK command.

    $ns connect $tcp $sink

    Step 5: Run and Execute the program.

    $ns run

    PROGRAM:

    set ns [new Simulator]

    set nf [open tcp.nam w]

    $ns namtrace-all $nf

    set tf [open out.tr w]

    $ns trace-all $tf

    proc finish {} {

    global ns nf tf

    $ns flush-trace

    close $nf

    close $tf

    exec nam tcp.nam &

    exit 0

    }

    set n0 [$ns node]

    set n1 [$ns node]

    set n2 [$ns node]

    set n3 [$ns node]

    set n4 [$ns node]

    set n5 [$ns node]

    $ns duplex-link $n0 $n4 1Mb 50ms DropTail

  • $ns duplex-link $n1 $n4 1Mb 50ms DropTail

    $ns duplex-link $n2 $n5 1Mb 1ms DropTail

    $ns duplex-link $n3 $n5 1Mb 1ms DropTail

    $ns duplex-link $n4 $n5 1Mb 50ms DropTail

    $ns duplex-link-op $n4 $n5 queuePos 0.5

    set tcp [new Agent/TCP]

    $ns attach-agent $n0 $tcp

    set sink [new Agent/TCPSink]

    $ns attach-agent $n2 $sink

    $ns connect $tcp $sink

    set ftp [new Application/FTP]

    $ftp attach-agent $tcp

    $ns at 0.0 "$ftp start"

    $ns at 2.5 "$ftp stop"

    $ns at 3 "finish"

    $ns run

    OUTPUT:

  • RESULT:

    Thus, the program for implementing TCP was executed using NS-2 and output verified

    using Network Animator.

    PRE LAB (10) POST LAB (10) VIVA (10) TOTAL (30) TOT (10)

  • EX.NO: 7 ETHERNET CSMA/CD PROTOCOL

    DATE:

    AIM

    To study transmission of packets over Ethernet LAN and its CSMA/CD protocol

    ALGORITHM

    1. Create a simulator object

    2. Set different color for TCP and UDP traffic.

    3. Trace packets on all links onto NAM trace and text trace file

    4. Define finish procedure to close files, flush tracing and run NAM

    5. Create six nodes

    6. Specify the link characteristics between nodes

    7. Create a LAN with nodes n3, n4, n5 part of it

    8. Describe layout topology of nodes

    9. Add UDP agent for node n1

    10. Create CBR traffic on top of UDP and set traffic parameters.

    11. Add a null agent to node and connect it to udp source

    12. Add TCP agent for node n0

    13. Create FTP traffic for TCP and set its parameters

    14. Add a sink to TCP and connect it to source

    15. Schedule events as follows:

    a. Start CBR & FTP traffic flow at 0.3 and 0.8 respectively

    b. Stop CBR & FTP traffic flow at 7.5 and 7.0 respectively

    c. Call finish procedure at 8.0

    16. Start the scheduler

    17. Observe the transmission of packets over LAN

    18. View the simulated events and trace file analyze it

    19. Stop

  • PROGRAM

    #Lan simulation mac.tcl

    set ns [new Simulator]

    #define color for data flows

    $ns color 1 Purple

    $ns color 2 MAgenta

    #open tracefile

    set tracefile1 [open out.tr w]

    $ns trace-all $tracefile1

    #open nam file

    set namfile [open out.nam w]

    $ns namtrace-all $namfile

    #define the finish procedure

    proc finish {} {

    global ns tracefile1 namfile

    $ns flush-trace

    close $tracefile1

    close $namfile

    exec nam out.nam &

    exit 0

    }

    #create six nodes

    set n0 [$ns node]

    set n1 [$ns node]

    set n2 [$ns node]

    set n3 [$ns node]

    set n4 [$ns node]

    set n5 [$ns node]

    # Specify color and shape for nodes

    $n1 color MAgenta

    $n1 shape box

    $n5 color MAgenta

    $n5 shape box

    $n0 color Purple

    $n4 color Purple

    #create links between the nodes

    $ns duplex-link $n0 $n2 2Mb 10ms DropTail

    $ns duplex-link $n1 $n2 2Mb 10ms DropTail

    $ns simplex-link $n2 $n3 0.3Mb 100ms DropTail

    $ns simplex-link $n3 $n2 0.3Mb 100ms DropTail

    # Create a LAN

    set lan [$ns newLan "$n3 $n4 $n5" 0.5Mb 40ms LL Queue/DropTail

    MAC/Csma/Cd Channel]

    #Give node position

    $ns duplex-link-op $n0 $n2 orient right-down

  • $ns duplex-link-op $n1 $n2 orient right-up

    $ns simplex-link-op $n2 $n3 orient right

    $ns simplex-link-op $n3 $n2 orient left

    #setup TCP connection

    set tcp [new Agent/TCP/Newreno]

    $ns attach-agent $n0 $tcp

    set sink [new Agent/TCPSink/DelAck]

    $ns attach-agent $n4 $sink

    $ns connect $tcp $sink

    $tcp set fid_ 1

    $tcp set packet_size_ 552

    #set ftp over tcp connection

    set ftp [new Application/FTP]

    $ftp attach-agent $tcp

    #setup a UDP connection

    set udp [new Agent/UDP]

    $ns attach-agent $n1 $udp

    set null [new Agent/Null]

    $ns attach-agent $n5 $null

    $ns connect $udp $null

    $udp set fid_ 2

    #setup a CBR over UDP connection

    set cbr [new Application/Traffic/CBR]

    $cbr attach-agent $udp

    $cbr set type_ CBR

    $cbr set packet_size_ 1000

    $cbr set rate_ 0.05Mb

    $cbr set random_ false

    #scheduling the events

    $ns at 0.0 "$n0 label TCP_Traffic"

    $ns at 0.0 "$n1 label UDP_Traffic"

    $ns at 0.3 "$cbr start"

    $ns at 0.8 "$ftp start"

    $ns at 7.0 "$ftp stop"

    $ns at 7.5 "$cbr stop"

    $ns at 8.0 "finish"

    $ns run

  • OUTPUT

    $ ns mac.tcl

  • RESULT

    Thus broadcasting of packets over ethernet LAN and collision of packets was observered.

    PRE LAB (10) POST LAB (10) VIVA (10) TOTAL (30) TOT (10)

  • EX.NO: 8 DISTANCE VECTOR ROUTING PROTOCOL

    DATE:

    AIM

    To simulate a link failure and to observe distance vector routing protocol in action.

    ALGORITHM

    1. Create a simulator object

    2. Set routing protocol to Distance Vector routing

    3. Trace packets on all links onto NAM trace and text trace file

    4. Define finish procedure to close files, flush tracing and run NAM

    5. Create eight nodes

    6. Specify the link characteristics between nodes

    7. Describe their layout topology as a octagon

    8. Add UDP agent for node n1

    9. Create CBR traffic on top of UDP and set traffic parameters.

    10. Add a sink agent to node n4

    11. Connect source and the sink

    12. Schedule events as follows:

    . Start traffic flow at 0.5

    b. Down the link n3-n4 at 1.0

    c. Up the link n3-n4 at 2.0

    d. Stop traffic at 3.0

    . Call finish procedure at 5.0

    13. Start the scheduler

    14. Observe the traffic route when link is up and down

    15. View the simulated events and trace file analyze it

    16. Stop

  • PROGRAM

    #Distance vector routing protocol distvect.tcl

    #Create a simulator object

    set ns [new Simulator]

    #Use distance vector routing

    $ns rtproto DV

    #Open the nam trace file

    set nf [open out.nam w]

    $ns namtrace-all $nf

    # Open tracefile

    set nt [open trace.tr w]

    $ns trace-all $nt

    #Define 'finish' procedure

    proc finish {} {

    global ns nf

    $ns flush-trace

    #Close the trace file

    close $nf

    #Execute nam on the trace file

    exec nam -a out.nam &

    exit 0

    }

    # Create 8 nodes

    set n1 [$ns node]

    set n2 [$ns node]

    set n3 [$ns node]

    set n4 [$ns node]

    set n5 [$ns node]

    set n6 [$ns node]

    set n7 [$ns node]

    set n8 [$ns node]

    # Specify link characterestics

    $ns duplex-link $n1 $n2 1Mb 10ms DropTail

    $ns duplex-link $n2 $n3 1Mb 10ms DropTail

    $ns duplex-link $n3 $n4 1Mb 10ms DropTail

    $ns duplex-link $n4 $n5 1Mb 10ms DropTail

    $ns duplex-link $n5 $n6 1Mb 10ms DropTail

    $ns duplex-link $n6 $n7 1Mb 10ms DropTail

    $ns duplex-link $n7 $n8 1Mb 10ms DropTail

    $ns duplex-link $n8 $n1 1Mb 10ms DropTail

    # specify layout as a octagon

    $ns duplex-link-op $n1 $n2 orient left-up

    $ns duplex-link-op $n2 $n3 orient up

    $ns duplex-link-op $n3 $n4 orient right-up

    $ns duplex-link-op $n4 $n5 orient right

    $ns duplex-link-op $n5 $n6 orient right-down

  • $ns duplex-link-op $n6 $n7 orient down

    $ns duplex-link-op $n7 $n8 orient left-down

    $ns duplex-link-op $n8 $n1 orient left

    #Create a UDP agent and attach it to node n1

    set udp0 [new Agent/UDP]

    $ns attach-agent $n1 $udp0

    #Create a CBR traffic source and attach it to udp0

    set cbr0 [new Application/Traffic/CBR]

    $cbr0 set packetSize_ 500

    $cbr0 set interval_ 0.005

    $cbr0 attach-agent $udp0

    #Create a Null agent (a traffic sink) and attach it to node n4

    set null0 [new Agent/Null]

    $ns attach-agent $n4 $null0

    #Connect the traffic source with the traffic sink

    $ns connect $udp0 $null0

    #Schedule events for the CBR agent and the network dynamics

    $ns at 0.0 "$n1 label Source"

    $ns at 0.0 "$n4 label Destination"

    $ns at 0.5 "$cbr0 start"

    $ns rtmodel-at 1.0 down $n3 $n4

    $ns rtmodel-at 2.0 up $n3 $n4

    $ns at 4.5 "$cbr0 stop"

    #Call the finish procedure after 5 seconds of simulation time

    $ns at 5.0 "finish"

    #Run the simulation

    $ns run

  • OUTPUT

    $ ns distvect.tcl

  • RESULT

    Thus, performance of distance vector protocol and routing path was studied using NS2.

    PRE LAB (10) POST LAB (10) VIVA (10) TOTAL (30) TOT (10)

  • EX.NO:9 STUDY OF UDP PERFORMANCE

    DATE:

    AIM

    To study the performance of UDP by simulating a simple network

    ALGORITHM

    1. Create a simulator object

    2. Define different color for data flows

    3. Trace all events in a nam file.

    4. Create four nodes n0, n1, n2 and n3

    5. Describe their layout topology

    6. Specify the link capacity between nodes

    7. Monitor queue on the link n2 to n3 vertically 90

    8. Create a UDP agents udp0, udp1 and attach it to nodes n0 and n1 respectively

    9. Create a CBR traffic cbr0, cbr1 and attach it to udp0 and udp1 respectively

    10. Create a traffic sink and attach it to node n3

    11. Connect sources to the sink

    12. Label the nodes

    13. Schedule cbr0 to start at 0.5 and stop at 4.5 seconds

    14. Schedule cbr1 to start at 1.0 and stop at 4.0 seconds

    15. Call finish procedure at 5.0 seconds

    16. Run the simulation

    17. Execute NAM on the trace file

    18. Observe simulated events on the NAM and packet flow on link n2 to n3

    19. Stop

  • PROGRAM

    #Study of UDP performance - UDP.tcl

    #Create a simulator object

    set ns [new Simulator]

    #Define different colors for data flows

    $ns color 1 Blue

    $ns color 2 Red

    #Open the nam trace file

    set nf [open out.nam w]

    $ns namtrace-all $nf

    #Create four nodes

    set 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 1Mb 10ms DropTail

    $ns duplex-link $n1 $n2 1Mb 10ms DropTail

    $ns duplex-link $n3 $n2 1Mb 10ms SFQ

    #Specify layout of nodes

    $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 the link 23 vertically

    $ns duplex-link-op $n2 $n3 queuePos 0.5

    #Create a UDP agent and attach it to node n0

    set udp0 [new Agent/UDP]

    $udp0 set class_ 1

    $ns attach-agent $n0 $udp0

    # Create a CBR traffic source and attach it to udp0

    set cbr0 [new Application/Traffic/CBR]

    $cbr0 set packetSize_ 500

    $cbr0 set interval_ 0.005

    $cbr0 attach-agent $udp0

    #Create a UDP agent and attach it to node n1

    set udp1 [new Agent/UDP]

    $udp1 set class_ 2

    $ns attach-agent $n1 $udp1

    # Create a CBR traffic source and attach it to udp1

    set cbr1 [new Application/Traffic/CBR]

    $cbr1 set packetSize_ 500

    $cbr1 set interval_ 0.005

    $cbr1 attach-agent $udp1

    #Create a Null agent (a traffic sink) and attach it to node n3

    set null0 [new Agent/Null]

    $ns attach-agent $n3 $null0

  • #Connect traffic sources with the traffic sink

    $ns connect $udp0 $null0

    $ns connect $udp1 $null0

    #Define finish procedure

    proc finish {} {

    global ns nf

    $ns flush-trace

    #Close the trace file

    close $nf

    #Execute nam on the trace file

    exec nam -a out.nam &

    exit 0

    }

    #Define label for nodes

    $ns at 0.0 "$n0 label Sender1"

    $ns at 0.0 "$n1 label Sender2"

    $ns at 0.0 "$n2 label Router"

    $ns at 0.0 "$n3 label Receiver"

    #Schedule events for the CBR agents

    $ns at 0.5 "$cbr0 start"

    $ns at 1.0 "$cbr1 start"

    $ns at 4.0 "$cbr1 stop"

    $ns at 4.5 "$cbr0 stop"

    #Call finish procedure after 5 seconds of simulation time

    $ns at 5.0 "finish"

    #Run the simulation

    $ns run

  • OUTPUT

    $ ns UDP.tcl

    RESULT

    Thus the performance of UDP and basic network terminologies were studied using NS2.

    PRE LAB (10) POST LAB (10) VIVA (10) TOTAL (30) TOT (10)

  • EX.NO: 10 STUDY OF TCP PERFORMANCE

    DATE:

    AIM

    To study the performance of a TCP network with droptail queue mechanism on the

    gateway

    ALGORITHM

    1. Create a simulator object

    2. Define different flows for data flows

    3. Trace all events in a nam file and text file

    4. Create source nodes (s1, s2, s3), gateway (G) and receiver (r)

    5. Describe their layout topology

    6. Specify the link between nodes

    7. Define the queue size between nodes G and r as 5

    8. Monitor queue on all links vertically 90

    9. Create TCP agents tcp1, tcp2, tcp3 and attach it to nodes s1, s2 and s3 respectively

    10. Create three TCP sinks and attach it to node r

    11. Connect traffic sources to the sink

    12. Create FTP agents ftp1, ftp2, ftp3 and attach it to tcp1, tcp2 and tcp3 respectively

    13. Label the nodes at start time

    14. Schedule ftp1, ftp2, ftp3 to start at 0.1 and stop at 5.0 seconds

    15. Call finish procedure at 5.25 seconds

    16. Run the simulation

    17. Execute NAM on the trace file

    18. Observe the simulated events on the NAM editor and packet flow on link G to r

    19. View the trace file and analyse the events

    20. Stop

  • PROGRAM

    #Study of TCP performance - TCP.tcl

    #Create a simulator object

    set ns [new Simulator]

    #Open trace files

    set f [open droptail-queue-out.tr w]

    $ns trace-all $f

    #Open the nam trace file

    set nf [open droptail-queue-out.nam w]

    $ns namtrace-all $nf

    #s1, s2 and s3 act as sources.

    set s1 [$ns node]

    set s2 [$ns node]

    set s3 [$ns node]

    #G acts as a gateway

    set G [$ns node]

    #r acts as a receiver

    set r [$ns node]

    #Define different colors for data flows

    $ns color 1 red

    $ns color 2 SeaGreen

    $ns color 3 blue

    #Create links between the nodes

    $ns duplex-link $s1 $G 6Mb 10ms DropTail

    $ns duplex-link $s2 $G 6Mb 10ms DropTail

    $ns duplex-link $s3 $G 6Mb 10ms DropTail

    $ns duplex-link $G $r 3Mb 10ms DropTail

    #Define the layout of the nodes

    $ns duplex-link-op $s1 $G orient right-up

    $ns duplex-link-op $s2 $G orient right

    $ns duplex-link-op $s3 $G orient right-down

    $ns duplex-link-op $G $r orient right

    #Define the queue size for the link between node G and r

    $ns queue-limit $G $r 5

    #Monitor the queues for links vertically

    $ns duplex-link-op $s1 $G queuePos 0.5

    $ns duplex-link-op $s2 $G queuePos 0.5

    $ns duplex-link-op $s3 $G queuePos 0.5

    $ns duplex-link-op $G $r queuePos 0.5

    #Create a TCP agent and attach it to node s1

    set tcp1 [new Agent/TCP/Reno]

    $ns attach-agent $s1 $tcp1

    $tcp1 set window_ 8

    $tcp1 set fid_ 1

    #Create a TCP agent and attach it to node s2

    set tcp2 [new Agent/TCP/Reno]

  • $ns attach-agent $s2 $tcp2

    $tcp2 set window_ 8

    $tcp2 set fid_ 2

    #Create a TCP agent and attach it to node s3

    set tcp3 [new Agent/TCP/Reno]

    $ns attach-agent $s3 $tcp3

    $tcp3 set window_ 4

    $tcp3 set fid_ 3

    #Create TCP sink agents and attach them to node r

    set sink1 [new Agent/TCPSink]

    set sink2 [new Agent/TCPSink]

    set sink3 [new Agent/TCPSink]

    $ns attach-agent $r $sink1

    $ns attach-agent $r $sink2

    $ns attach-agent $r $sink3

    #Connect the traffic sources with the traffic sinks

    $ns connect $tcp1 $sink1

    $ns connect $tcp2 $sink2

    $ns connect $tcp3 $sink3

    #Create FTP applications and attach them to agents

    set ftp1 [new Application/FTP]

    $ftp1 attach-agent $tcp1

    set ftp2 [new Application/FTP]

    $ftp2 attach-agent $tcp2

    set ftp3 [new Application/FTP]

    $ftp3 attach-agent $tcp3

    #Define a 'finish' procedure

    proc finish {} {

    global ns

    $ns flush-trace

    puts "running nam..."

    exec nam -a droptail-queue-out.nam &

    exit 0

    }

    #Define label for nodes

    $ns at 0.0 "$s1 label Sender1"

    $ns at 0.0 "$s2 label Sender2"

    $ns at 0.0 "$s3 label Sender3"

    $ns at 0.0 "$G label Gateway"

    $ns at 0.0 "$r label Receiver"

    #Schedule ftp events

    $ns at 0.1 "$ftp1 start"

    $ns at 0.1 "$ftp2 start"

    $ns at 0.1 "$ftp3 start"

    $ns at 5.0 "$ftp1 stop"

    $ns at 5.0 "$ftp2 stop"

  • $ns at 5.0 "$ftp3 stop"

    #Call finish procedure after 5 seconds of simulation time

    $ns at 5.25 "finish"

    #Run the simulation

    $ns run

    OUTPUT

    $ ns TCP.tcl

  • RESULT

    Thus the behavior of TCP was observed and the basic terminologies of TCP transmission

    were understood.

    PRE LAB (10) POST LAB (10) VIVA (10) TOTAL (30) TOT (10)


Recommended