Sei sulla pagina 1di 87

BCSCCS506R02-COMPUTER NETWORKS LAB

1.a

1.b
1.c

E:\> msg * hi

2.a

import java.io.*;

import java.net.*;

class TestServer

public static void main(String ar[])

try {

ServerSocket ss=new ServerSocket(2000);

System.out.println("\n Waiting .....");

Socket s=ss.accept();

System.out.println("Accepted..");

InputStream in=s.getInputStream();

byte b[]=new byte[7];

in.read(b,0,6);

System.out.println(new String(b));

catch(Exception e)

System.out.println(e);

}
}

----------------------------------

import java.io.*;

import java.net.*;

class TestClient

public static void main(String ar[])

try {

Socket s=new Socket("localhost",2000);

OutputStream out=s.getOutputStream();

out.write("Hello".getBytes());

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

}
2.b

import java.net.DatagramPacket;

import java.net.DatagramSocket;

import java.net.InetAddress;

public class UDPsend {

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

DatagramSocket ds = new DatagramSocket();

String str = "hello world";

InetAddress ia = InetAddress.getByName("192.169.0.231");

DatagramPacket dp = new DatagramPacket(str.getBytes(), str.length(), ia, 3000);

ds.send(dp);

ds.close();
}

import java.net.DatagramPacket;

import java.net.DatagramSocket;

public class UDPreceive {

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

DatagramSocket ds = new DatagramSocket(3000);

byte[] buf = new byte[1024];

DatagramPacket dp = new DatagramPacket(buf, 1024);

ds.receive(dp);

String strRecv = new String(dp.getData(), 0, dp.getLength()) + " from "

+ dp.getAddress().getHostAddress() + ":" + dp.getPort();

System.out.println(strRecv);

ds.close();

}
3. Secured communication through encryption and decryption of messages.

import java.io.*;

import java.net.*;

class serverencrypt

public static void main(String args[])

{
try

ServerSocket ss = new ServerSocket(3000);

Socket s = ss.accept();

System.out.println("Connected...");

byte b[]= new byte[7];

OutputStream out = s.getOutputStream();

String t ="Amazing";

String k = new String();

int j;

int key = 3;

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

{ j=(int)t.charAt(i);

k=k+(char)(j+key);

System.out.println("\n Encrypted form "+k);

out.write(k.getBytes());}

catch(Exception e)

System.out.println(e);

}}

4. Program for Remote procedure call under client server environment (RMI)

/* Program PrimeServer.java */
import java.net.*;

import java.rmi.*;

import java.io.*;

public class PrimeServer {

public static void main(String args[]) {

try {

System.out.println("waiting for client.....");

PrimeServerImpl prime1ServerImpl = new PrimeServerImpl();

Naming.rebind("PrimeServer", prime1ServerImpl);

catch(Exception e) {

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

/* Program PrimeClient.java */

import java.rmi.*;

import java.io.*;

public class PrimeClient

public static void main(String args[])

int n;
try {

String PrimeServerURL = "rmi://localhost/PrimeServer";

PrimeServerIntf prime1ServerIntf =

(PrimeServerIntf)Naming.lookup(PrimeServerURL);

//System.out.println("Enter n" +args[1]);

System.out.println("Enter n");

InputStreamReader ir=new InputStreamReader(System.in);

BufferedReader br=new BufferedReader(ir);

n=Integer.parseInt(br.readLine());

System.out.println("The count is: " + prime1ServerIntf.prime(n));

catch(Exception e) {

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

/* Program PrimeServerIntf */

import java.rmi.*;

public interface PrimeServerIntf extends Remote

int prime(int n) throws RemoteException;

/* Program PrimeServerImpl.java */
import java.io.*;

import java.rmi.*;

import java.rmi.server.*;

public class PrimeServerImpl extends UnicastRemoteObject

implements PrimeServerIntf {

public PrimeServerImpl() throws RemoteException {}

public int prime(int n) throws RemoteException {

int count=0;

int i;

if(n==1)

System.out.println("1 is neither prime nor composite");

System.exit(0);

for(i=2;i<n/2;i++)

if(n%i==0)

count++;

if(count>0)

System.out.println("the entered number is not prime");

}
else

System.out.println("the entered no is prime");

return count;

6.

a. Program for error correction using CRC

/**** TCPServerCRC.java ***/

import java.io.*;import java.util.*;


import java.net.*;

import java.nio.*;

class TcpServerCRC

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

{try{

ServerSocket ss = new ServerSocket(2222);

Socket soc=ss.accept();

byte j;String s;StringBuffer sb=new StringBuffer();

String str=new BufferedReader(new


InputStreamReader(soc.getInputStream())).readLine();

InputStream fin = new FileInputStream(str);int m=0;

do

j = (byte)fin.read();

//s[m]=j.toString();

sb.append((char)j);

m++;}while(j!=-1);

int[] divisor;int divisor_bits,tot_length;int[] div; int[] rem;int[] crc;

String s1="";

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

s=sb.toString();System.out.println("original data "+s);

System.out.println("Enter number of bits in divisor : ");

divisor_bits=Integer.parseInt(br.readLine());
divisor=new int[divisor_bits];

System.out.println("Enter Divisor bits : ");

for(int i=0; i<divisor_bits; i++)

divisor[i]=Integer.parseInt(br.readLine());

tot_length=s.length()+divisor_bits-1;//System.out.println("length "+tot_length);

div=new int[tot_length];

rem=new int[tot_length];

crc=new int[tot_length];

s="["+s+"]";

//System.out.println("data");

String s8[]=s.replaceAll("\\[","").replaceAll("\\]","").split("");int data[]=new int[s8.length];

//System.out.println("s8 length "+s8.length);

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

try

{data[i]=Integer.parseInt(s8[i]);}catch(Exception e){}}

/*for(int i=0;i<data.length;i++)

try

{System.out.print(data[i]);

}
catch(Exception e){}}

*/System.out.println();

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

try{ div[i]=data[i]; }catch(Exception e){} }

System.out.print("Dividend (after appending 0's) are : ");

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

{System.out.print(div[i]); }

System.out.println();

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

rem[i] = div[i];

rem=divide(div, divisor, rem);

for(int i=0;i<div.length;i++) //append dividend and ramainder

crc[i]=(div[i]^rem[i]);
}

System.out.println();

System.out.println("CRC code : ");

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

{ System.out.print(crc[i]);}

System.out.println();

//s.replaceAll("\\[","").replaceAll("\\]","").split("")

//Arrays.sort(crc);

//String[]
a=Arrays.toString(crc).replaceAll("\\[","").replaceAll("\\]","").replaceAll("\\,,","").replaceAll("\\,
","").split("");

// a=crc.replaceAll("\\[","").replaceAll("\\]","").replaceAll("\\,","").split("");

//s1=Arrays.toString(a);

String a=Arrays.toString(crc);

String ar[]=a.substring(1,a.length()-1).split(", ,, ,");

System.out.println(Arrays.toString(ar));

s1=Arrays.toString(ar);

String s9[]=s1.replaceAll("\\[","").replaceAll("\\]","").replaceAll("\\,","").split("");

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

{
System.out.print(s9[i].toString());

// System.out.println("msg to b sent "+s1);

File f1=new File("t.txt");

FileOutputStream fs=new FileOutputStream(f1);

if(s1!=null)

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

byte jj[]=s9[i].getBytes();

fs.write(jj);

}}fs.close();

InputStream f=new FileInputStream("t.txt");

do

j=(byte)f.read();

soc.getOutputStream().write(j);

}while(j!=-1);

}}

catch(Exception e)

{}

}
static int[] divide(int div[],int divisor[], int rem[])

int cur=0;

while(true)

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

rem[cur+i]=(rem[cur+i]^divisor[i]);

while(rem[cur]==0 && cur!=rem.length-1)

cur++;

if((rem.length-cur)<divisor.length)

break;

return rem;

/**** TCPClientCRC.java ****/

import java.io.*;

import java.net.*;

public class TcpclientCRC

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

{try{
Socket socket = new Socket("127.0.0.1",2222);

byte b;

StringBuffer sb = new StringBuffer();

InputStream in = socket.getInputStream();int e=0;

PrintStream out = new PrintStream(new


DataOutputStream(socket.getOutputStream()));

String filename=new BufferedReader(new


InputStreamReader(System.in)).readLine();

out.println(filename);

while((b=(byte)in.read())!=-1)

sb.append((char)b);

String s1=sb.toString();System.out.println(s1);

//String s8[]=s1.replaceAll("\\[","").replaceAll("\\]","").split("");

//int data[]=new int[s8.length];

//s="["+s+"]";

String s8[]=s1.replaceAll("\\ ","").split(",");

int data[]=new int[10];


//data[0]=Integer.parseInt(s8[0]);

System.out.println("s8 length "+s8.length);

//int j=0;

String az=s8[0].toString();

System.out.println("string az "+az+" length "+az.length());

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

String s="";

/*if(s8[i].startsWith(","))

}*/

data[i]=Integer.parseInt(s8[i]);

//j++;

//i=i+2;

System.out.println("data");

for(int i=0;i<1;i++)

{
System.out.print(data[i]);

System.out.println();

System.out.print("string");

System.out.println();

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

System.out.print(s8[i].toString());

az="["+az+"]";

String sbuf[]=az.replaceAll("\\[","").replaceAll("\\]","").split("");

int datacrc[]=new int[sbuf.length];

System.out.println("sbuf length "+sbuf.length);

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

try

{datacrc[i]=Integer.parseInt(sbuf[i]);
}catch(Exception ex){}

System.out.println("datacrc");

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

try

{System.out.print(datacrc[i]);

catch(Exception ex){}

System.out.println();

int[] divisor=new int[4];

int[] rem=new int[datacrc.length];

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

System.out.println("enter the divisor bits");

for(int i=0; i<4; i++)

{ divisor[i]=Integer.parseInt(br.readLine());}

for(int j=0; j<datacrc.length; j++)

rem[j] =datacrc[j];

}
rem=divide(datacrc, divisor, rem);

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

if(rem[i]!=0)

System.out.println("result : Error");

break;

if(i==rem.length-1)

System.out.println("result :No Error");

}catch(Exception e){}}

static int[] divide(int div[],int divisor[], int rem[])

int cur=0;

while(true)

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

rem[cur+i]=(rem[cur+i]^divisor[i]);
while(rem[cur]==0 && cur!=rem.length-1)

cur++;

if((rem.length-cur)<divisor.length)

break;

return rem;

b. Program for error detection using hamming code

/* program TestServer1ham.java */

import java.io.*;

import java.net.*;

import java.util.*;

public class Testserver1ham

static int set_parity_bit(int a[])

int count=0; //........Initialising count to zero which will count the number of 1.

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

if(a[i]==1)

++count; //............Incrementing count if value in array "a" is 1.

if((count%2)==0)

return 0;//........Returning 0 if even number of 1

else

return 1;//........Returning 1 if odd number of 1

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

ServerSocket ss;

Socket s;

try

System.out.println("waiting ");

ss=new ServerSocket(8085);

s=ss.accept();

System.out.println("connection established");

Scanner scr= new Scanner(System.in);

System.out.println("HAMMING CODE");

System.out.println();

System.out.println("Enter 4 data bits");

int n=4;
int d[]=new int[4];

for(int i=n-1;i>=0;--i)

System.out.println("Enter the value of D"+(i+1));

d[i]=scr.nextInt();

/*.............. Formula for calculating 2^k>=n+k+1 ...............*/

int k=0;// k stands for number of parity bits.Initializing it to zero.

while(Math.pow(2,k)<(n+k+1)) // Calculating the value of k(number of parity bits).

++k;

System.out.println();

System.out.println(k+" parity bits are required for the transmission of data bits.");

int parity[]=new int[k]; //..........Array to store parity bits

int h[]=new int[n+k+1];//.........Array to hold the hamming code.(n+k+1) as we start from


pos 1.

/********** Initialising array h[] to -1 ************/

for(int i=0;i<=7;++i)

h[i]=-1;
int count=0;

int c=2;

while(count<4)

++c;

if(c==4)

continue;

h[c]=d[count];

++count;

int p1[]={h[1],h[3],h[5],h[7]};

int p2[]={h[2],h[3],h[6],h[7]};

int p3[]={h[4],h[5],h[6],h[7]};

/************Setting the value of parity bit*************/

parity[0]=set_parity_bit(p1);

parity[1]=set_parity_bit(p2);

parity[2]=set_parity_bit(p3);

/************Inserting the parity bits in the hamming code**********/

h[1]=parity[0];

h[2]=parity[1];

h[4]=parity[2];

System.out.println("\nSENDER:");
System.out.print("\nThe data bits entered are: ");

for(int i=3;i>=0;--i)

System.out.print(d[i]+" ");

System.out.println("\nThe Parity bits are: ");

for(int i=2;i>=0;--i)

System.out.println("Value of P"+(i+1)+" is "+parity[i]+" ");

System.out.print("\nThe Hamming code is as follows ");

for(int i=(n+k);i>0;--i)

System.out.print(h[i]+" ");

OutputStream out= s.getOutputStream();

byte t[]=new byte[10];int i=0;byte x;

while((x=(byte)h[i])!=-1)

t[i]=x;

i++;

out.write(t);

}catch(Exception e){System.out.println("Exception:"+e);}

/* TestClient1ham.java */

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

import java.util.*;

class Testclient1ham

static int set_parity_bit(int a[])

int count=0; //........Initialising count to zero which will count the number of 1.

int l=a.length;

for(int i=0;i<l;++i)

if(a[i]==1)

++count; //............Incrementing count if value in array "a" is 1.

if((count%2)==0)

return 0;//........Returning 0 if even number of 1

else

return 1;//........Returning 1 if odd number of 1

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

try

Socket s=new Socket("127.0.0.1",8085);

byte b[]= new byte[10];

InputStream in=s.getInputStream();in.read(b,0,10);
Scanner scr=new Scanner(System.in);

int n=4;int k=0;

while(Math.pow(2,k)<(n+k+1)) // Calculating the value of k(number of parity bits).

++k;

System.out.println();

int parity[]=new int[k];

int h[]=new int[n+k+1];

System.out.println("Enter the hamming code with error at any position of your


choice.\nNOTE: ERROR should be present only at one bit position");

for(int i=7;i>0;--i)

h[i]=scr.nextInt();

int p4[]={h[1],h[3],h[5],h[7]};

int p5[]={h[2],h[3],h[6],h[7]};

int p6[]={h[4],h[5],h[6],h[7]};

parity[0]=set_parity_bit(p4);

parity[1]=set_parity_bit(p5);

parity[2]=set_parity_bit(p6);

int
position=(int)(parity[2]*Math.pow(2,2)+parity[1]*Math.pow(2,1)+parity[0]*Math.pow(2,0));

System.out.println("\nRECEIVER:");
System.out.println("Error is detected at position "+position+" at the receiving end.");

System.out.println("Correcting the error.... ");

if(h[position]==1)

h[position]=0;

else

h[position]=1;

System.out.print("The correct code is ");

for(int i=7;i>0;--i)

System.out.print(h[i]+" ");

catch(Exception e)

System.out.println(e);

}
7. RS232
“RS232EXAMPLE.JAVA”

import gnu.io.CommPortIdentifier;

import gnu.io.SerialPort;

import gnu.io.SerialPortEventListener;

import gnu.io.PortInUseException;

import gnu.io.*;

import java.awt.*;

import java.awt.event.*;

import java.io.*;

import java.util.*;

public class RS232Example extends Frame implements ActionListener, SerialPortEventListener

TextField tf = new TextField(20);

Button sd = new Button("Send");


public TextArea ta = new TextArea(10, 50);

OutputStream out;

InputStream in;

byte[] buffer = new byte[1024];

int tail = 0;

public RS232Example(String Title)

super(Title);

setLayout(new FlowLayout());

add(tf);

add(sd);

add(ta);

sd.addActionListener(this);

addWindowListener(new wa(this));

public void actionPerformed(ActionEvent ae)

String mes = tf.getText()+"\n";

send(mes.getBytes());

public void serialEvent(SerialPortEvent event)

switch(event.getEventType())

case SerialPortEvent.BI:
case SerialPortEvent.OE:

case SerialPortEvent.FE:

case SerialPortEvent.PE:

case SerialPortEvent.CD:

case SerialPortEvent.CTS:

case SerialPortEvent.DSR:

case SerialPortEvent.RI:

case SerialPortEvent.OUTPUT_BUFFER_EMPTY:

break;

case SerialPortEvent.DATA_AVAILABLE:

byte b;

try

while((b = (byte)in.read()) != -1)

if (b=='\n')

onMessage();

else

buffer[tail] = b;

tail++;

}
onMessage();

catch (IOException e){System.out.println("IO Exception");}

public void send(byte[] bytes)

try {

ta.appendText("SENDING: " + new String(bytes, 0, bytes.length));

out.write(bytes);

out.flush();

catch (IOException e)

e.printStackTrace();

public void connect(String portName) throws Exception

//CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);

ta.appendText("connecting...\n");

try

{
SerialPort serialPort = (SerialPort) portIdentifier.open("RS232Example", 2000);

try

serialPort.addEventListener(this);

} catch (TooManyListenersException e) {}

serialPort.notifyOnDataAvailable(true);

serialPort.setSerialPortParams(38400, SerialPort.DATABITS_8,
SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

out = serialPort.getOutputStream();

in = serialPort.getInputStream();

catch (PortInUseException e){

System.out.println("Port in use! Run again by giving another port name as argument");

System.exit(0);

private void onMessage() {

if (tail!=0) {

String message = new String(buffer, 0, tail);

ta.appendText("RECEIVED : " + message+"\n");

if ("BYE".equals(message)) {

send("ACK\n".getBytes());

this.dispose();

System.exit(0);

}
else if ("ACK".equals(message)) {

this.dispose();

System.exit(0);

tail = 0;

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

RS232Example re = new RS232Example(args[0]);

re.setVisible(true);

re.setSize(300, 300);

re.connect(args[0]);

class wa extends WindowAdapter {

RS232Example r;

public wa(RS232Example r){

this.r = r;

public void windowClosing(WindowEvent we){

r.setVisible(false);

r.dispose();

System.exit(0);
}

PROTOCOL.JAVA

public interface Protocol {

// protocol manager handles each received byte

void onReceive(byte b);

// protocol manager handles broken stream

void onStreamClosed();

ListAvailablePorts.java

import gnu.io.CommPortIdentifier;

import java.util.Enumeration;

public class ListAvailablePorts {

public void list() {

Enumeration ports = CommPortIdentifier.getPortIdentifiers();

while(ports.hasMoreElements())

System.out.println(((CommPortIdentifier)ports.nextElement()).getName());

}
public static void main(String[] args) {

new ListAvailablePorts().list();

Commportreceiver.java

import java.io.IOException;

import java.io.InputStream;

public class CommPortReceiver extends Thread {

InputStream in;

Protocol protocol = new Protocolmpl();

public CommPortReceiver(InputStream in) {

this.in = in;

public void run() {

try {

int b;

while(true) {

// if stream is not bound in.read() method returns -1

while((b = in.read()) != -1) {

protocol.onReceive((byte) b);
}

protocol.onStreamClosed();

// wait 10ms when stream is broken and check again

sleep(10);

} catch (IOException e) {

e.printStackTrace();

} catch (InterruptedException e) {

e.printStackTrace();

COMMPORTSENDER.JAVA

import java.io.IOException;

import java.io.OutputStream;

public class CommPortSender {

static OutputStream out;

public static void setWriterStream(OutputStream out) {

CommPortSender.out = out;

}
public static void send(byte[] bytes) {

try {

System.out.println("SENDING: " + new String(bytes, 0, bytes.length));

// sending through serial port is simply writing into OutputStream

out.write(bytes);

out.flush();

} catch (IOException e) {

e.printStackTrace();

------

8. SLIDING WINDOW PROTOCOL

A) GO BACK N

//Go-Back-N

import java.io.*;

import java.net.*;

import java.util.*;

public class GBNclient

public static void main(String args[])

{
try

while(true)

Socket s=new Socket("localhost",5555);

System.out.println("socket created");

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

String st=br.readLine();

System.out.println("the frames are:"+st+"\nenter the frame where there is an error:");

s.close();

s=new Socket("localhost",5555);

Scanner scanner=new Scanner(System.in);

String error=scanner.nextLine();

DataOutputStream out=new DataOutputStream(s.getOutputStream());

out.writeBytes(error);

System.out.println("sent");

s.close();

Thread.sleep(100);

}catch(Exception e)

{}

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

public class GBNserver

static int burst=5;

public static void main(String args[])

try

int x=0,i;

String error=" ";

while(true && x<20)

String data=error;

error=" ";

int len=data.length();

for(i=0;i<burst;i++,x++)

data+=(char)('A'+x);

System.out.println("the new set to be sent is:"+data);

ServerSocket ss=new ServerSocket(5555);

Socket s=ss.accept();

DataOutputStream out=new DataOutputStream(s.getOutputStream());

out.writeBytes(data);

System.out.println("sent");

s.close();

ss.close();
Thread.sleep(100);

ss=new ServerSocket(5555);

s=ss.accept();

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

System.out.println("waiting....");

error=br.readLine();

System.out.println("the error is at:"+error);

s.close();

ss.close();

}catch(Exception e)

{}

//Selective Repeat

//SERVER PGM

import java.io.*;

import java.net.*;

public class SRserver

static int burst=5;

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

try
{

int i, error=0;

//String err=" ";

while(true)

int x=error;

String data=" ";

int len=data.length();

for(i=0;i<len;i++,x++)

data+=(char)('A'+x);

System.out.println("\n The new window to be sent is:"+data);

ServerSocket ss=new ServerSocket(5555);

Socket s=ss.accept();

DataOutputStream out= new DataOutputStream(s.getOutputStream());

out.writeBytes(data);

System.out.println("\n sent");

s.close();

ss.close();

Thread.sleep(100);

ss=new ServerSocket(5555);

s=ss.accept();

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

System.out.println("\nwaiting");

error=Integer.parseInt(br.readLine());

System.out.println("\nError is at: "+error);


s.close();

ss.close();

catch(Exception e)

{}

---

//Selective Repeat

//CLIENT PGM

import java.io.*;

import java.net.*;

import java.util.*;

public class SRclient

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

try

while(true)

Socket s=new Socket("localhost",5555);

System.out.println("socket created");

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


System.out.println("make duplicate to retransmit");

String st=br.readLine();

System.out.println("The frames are: "+st);

System.out.println("Enter the first damaged frame: ");

s.close();

s=new Socket("localhost",5555);

Scanner scanner=new Scanner(System.in);

String error=scanner.nextLine();

DataOutputStream out=new DataOutputStream(s.getOutputStream());

out.writeBytes(error);

System.out.println("sent");

s.close();

Thread.sleep(100);

}}

catch(Exception e)

{}

-------------
9. Distance vector

import java.io.*;

public class dist

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

int i,j,k,n,src;

int a[][]=new int[10][10];

String ch;

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

System.out.println("\n Enter the number of nodes = ");

n=Integer.parseInt(in.readLine());

for(i=1;i<=n;i++)

for(j=i;j<=n;j++)

if(i==j) a[i][j]=0;

else

{
System.out.println("\n Enter the distance between host : "+i+" and "+j);

a[i][j]=a[j][i]=Integer.parseInt(in.readLine());

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

for(i=1;i<=n;i++)

for(j=1;j<=n;j++) System.out.print(a[i][j]+" ");

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

for(k=1;k<=n;k++)

for(i=1;i<=n;i++)

for(j=1;j<=n;j++)

if(a[i][j]>a[i][k]+a[k][j])

a[i][j]=a[i][k]+a[k][j];

do

System.out.println("\n Enter the node to display the routing table : ");

src=Integer.parseInt(in.readLine());

for(j=1;j<=n;j++)

if(src!=j)

{
if(a[src][j]!=100) System.out.println("\n The shortest path from "+src+" to "+j+" is
"+a[src][j]);

else System.out.println("\n There is no path from"+src+" to "+j);

System.out.println("\n Do u want to continue(yes/no) : ");

ch=in.readLine();

}while(ch.equals("yes"));

// dijkstra

// A Java program for Dijkstra's single source shortest path algorithm.


// The program is for adjacency matrix representation of the graph
import java.util.*;
import java.lang.*;
import java.io.*;

class ShortestPath
{
// A utility function to find the vertex with minimum distance value,
// from the set of vertices not yet included in shortest path tree
static final int V=9;
int minDistance(int dist[], Boolean sptSet[])
{
// Initialize min value
int min = Integer.MAX_VALUE, min_index=-1;

for (int v = 0; v < V; v++)


if (sptSet[v] == false && dist[v] <= min)
{
min = dist[v];
min_index = v;
}

return min_index;
}

// A utility function to print the constructed distance array


void printSolution(int dist[], int n)
{
System.out.println("Vertex Distance from Source");
for (int i = 0; i < V; i++)
System.out.println(i+" \t\t "+dist[i]);
}

// Funtion that implements Dijkstra's single source shortest path


// algorithm for a graph represented using adjacency matrix
// representation
void dijkstra(int graph[][], int src) {
int dist[] = new int[V]; // The output array. dist[i] will hold
// the shortest distance from src to i

// sptSet[i] will true if vertex i is included in shortest


// path tree or shortest distance from src to i is finalized
Boolean sptSet[] = new Boolean[V];

// Initialize all distances as INFINITE and stpSet[] as false


for (int i = 0; i < V; i++)
{
dist[i] = Integer.MAX_VALUE;
sptSet[i] = false;
}

// Distance of source vertex from itself is always 0


dist[src] = 0;

// Find shortest path for all vertices


for (int count = 0; count < V-1; count++)
{
// Pick the minimum distance vertex from the set of vertices
// not yet processed. u is always equal to src in first
// iteration.
int u = minDistance(dist, sptSet);

// Mark the picked vertex as processed


sptSet[u] = true;

// Update dist value of the adjacent vertices of the


// picked vertex.
for (int v = 0; v < V; v++)

// Update dist[v] only if is not in sptSet, there is an


// edge from u to v, and total weight of path from src to
// v through u is smaller than current value of dist[v]
if (!sptSet[v] && graph[u][v]!=0 &&
dist[u] != Integer.MAX_VALUE &&
dist[u]+graph[u][v] < dist[v])
dist[v] = dist[u] + graph[u][v];
}

// print the constructed distance array


printSolution(dist, V);
}

// Driver method
public static void main (String[] args)
{
/* Let us create the example graph discussed above */
int graph[][] = new int[][]{{0, 4, 0, 0, 0, 0, 0, 8, 0},
{4, 0, 8, 0, 0, 0, 0, 11, 0},
{0, 8, 0, 7, 0, 4, 0, 0, 2},
{0, 0, 7, 0, 9, 14, 0, 0, 0},
{0, 0, 0, 9, 0, 10, 0, 0, 0},
{0, 0, 4, 0, 10, 0, 2, 0, 0},
{0, 0, 0, 14, 0, 2, 0, 1, 6},
{8, 11, 0, 0, 0, 0, 1, 0, 7},
{0, 0, 2, 0, 0, 0, 6, 7, 0}
};
ShortestPath t = new ShortestPath();
t.dijkstra(graph, 0);
}
}
Run on IDE

Output:

Vertex Distance from Source 0 01 42 12 3 19 4


21 5 11 6 97 88 14

10. Sys ctl commands

sysctl - configure kernel parameters at runtime

SYNOPSIS

sysctl [-n] [-e] variable ...

sysctl [-n] [-e] -w variable=value ...

sysctl [-n] [-e] -p <filename> (default /etc/sysctl.conf)

sysctl [-n] [-e] -a

sysctl [-n] [-e] -A


DESCRIPTION

sysctl is used to modify kernel parameters at runtime. The parameters available are those listed
under /proc/sys/. Procfs is required for sysctl(8) support in Linux. You can use sysctl(8) to both
read and write sysctl data.

PARAMETERS

variable

The name of a key to read from. An example is kernel.ostype. The '/' separator is also accepted in
place of a '.'.

variable=value

To set a key, use the form variable=value, where variable is the key and value is the value to set
it to. If the value contains quotes or characters which are parsed by the shell, you may need to
enclose the value in double quotes. This requires the -w parameter to use.

-n

Use this option to disable printing of the key name when printing values.

-e

Use this option to ignore errors about unknown keys.

-w

Use this option when you want to change a sysctl setting.

-p

Load in sysctl settings from the file specified or /etc/sysctl.conf if none given.

-a

Display all values currently available.

-A

Display all values currently available in table form.


EXAMPLES

/sbin/sysctl -a

/sbin/sysctl -n kernel.hostname

/sbin/sysctl -w kernel.domainname="example.com"

/sbin/sysctl -p /etc/sysctl.conf

sudo sysctl -p

without giving a specific file, it will read from /etc

/sysctl.conf by default.

TCP keep alive time

TCP keepalive

Transmission Control Protocol (TCP) keepalives are an optional feature, and if included must
default to off. The keepalive packet contains null data. In an Ethernet network, a keepalive
frame length is 60 bytes, while the server response to this, also a null data frame, is 54 bytes.[3]
There are three parameters related to keepalive:

Keepalive time is the duration between two keepalive transmissions in idle condition. TCP
keepalive period is required to be configurable and by default is set to no less than 2 hours.
Keepalive interval is the duration between two successive keepalive retransmissions, if
acknowledgement to the previous keepalive transmission is not received.

Keepalive retry is the number of retransmissions to be carried out before declaring that remote
end is not available.

------------------------------------------------------------------

Use sysctl -A to get a list of available kernel variables

and grep this list for net.ipv4 settings (sysctl -A | grep net.ipv4).

There should exist the following variables:

- net.ipv4.tcp_keepalive_time - time of connection inactivity after which

the first keep alive request is sent

- net.ipv4.tcp_keepalive_probes - number of keep alive requests retransmitted

before the connection is considered broken

- net.ipv4.tcp_keepalive_intvl - time interval between keep alive probes

You can manipulate with these settings using the following command:

sysctl -w net.ipv4.tcp_keepalive_time=60 net.ipv4.tcp_keepalive_probes=3


net.ipv4.tcp_keepalive_intvl=10

This sample command changes TCP keepalive timeout to 60 seconds with 3 probes,

10 seconds gap between each. With this, your application will detect dead TCP connections after
90 seconds (60 + 10 + 10 + 10).

11. Simulation of wired and wireless network

11.A) i. wired TCP


#Create a simulator object set ns [new Simulator] #Define different colors for data flows (for
NAM) $ns color 1 Blue $ns color 2 Red #Open the NAM trace file set nf [open out.nam w] $ns
namtrace-all $nf #Define a 'finish' procedure proc finish {} { global ns nf $ns flush-
trace #Close the NAM trace file close $nf #Execute NAM on the trace file
exec nam out.nam & exit 0 } #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 2Mb
10ms DropTail $ns duplex-link $n1 $n2 2Mb 10ms DropTail $ns duplex-link $n2 $n3 1.7Mb
20ms DropTail #Set Queue Size of link (n2-n3) to 10 $ns queue-limit $n2 $n3 10 #Give node
position (for NAM) $ns duplex-link-op $n0 $n2 orient right-down $ns duplex-link-op $n1 $n2
orient right-up $ns duplex-link-op $n2 $n3 orient right #Monitor the queue for link (n2-n3). (for
NAM) $ns duplex-link-op $n2 $n3 queuePos 0.5 #Setup a TCP connection set tcp [new
Agent/TCP] $tcp set class_ 2 $ns attach-agent $n0 $tcp set sink [new Agent/TCPSink] $ns
attach-agent $n3 $sink $ns connect $tcp $sink $tcp set fid_ 1 #Setup a FTP over TCP
connection set ftp [new Application/FTP] $ftp attach-agent $tcp $ftp set type_ FTP #Setup a
UDP connection set udp [new Agent/UDP] $ns attach-agent $n1 $udp set null [new Agent/Null]
$ns attach-agent $n3 $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_ 1mb $cbr set random_ false #Schedule events for the
CBR and FTP agents $ns at 0.1 "$cbr start" $ns at 1.0 "$ftp start" $ns at 4.0 "$ftp stop" $ns at 4.5
"$cbr stop" #Detach tcp and sink agents (not really necessary) $ns at 4.5 "$ns detach-agent $n0
$tcp ; $ns detach-agent $n3 $sink" #Call the finish procedure after 5 seconds of simulation time
$ns at 5.0 "finish" #Print CBR packet size and interval puts "CBR packet size = [$cbr set
packet_size_]" puts "CBR interval = [$cbr set interval_]" #Run the simulation $ns run

11.A ) ii. Wired UDP

set ns [new Simulator]

set nf1 [open out.nam w]

$ns namtrace-all $nf1

set n0 [$ns node]

set n1 [$ns node]


$ns duplex-link $n0 $n1 1Mb 25ms DropTail

set udp0 [new Agent/UDP]

$ns attach-agent $n0 $udp0

set cbr0 [new Application/Traffic/CBR]

$cbr0 set packetSize_ 500

$cbr0 set interval_ 0.05

$cbr0 attach-agent $udp0

set null0 [new Agent/Null]

$ns attach-agent $n1 $null0

$ns connect $udp0 $null0

$udp0 set class_ 1

$ns color 1 Blue


$ns at 0.3 "$cbr0 start"

$ns at 4.0 "$cbr0 stop"

proc finish {} {

global ns nf1

$ns flush-trace

close $nf1

exec nam out.nam &

exit 0

$ns at 5.0 "finish"

$ns run

11.b wireless ns2

#Copyright (c) 1997 Regents of the University of California.

# All rights reserved.

#
# Redistribution and use in source and binary forms, with or without

# modification, are permitted provided that the following conditions

# are met:

# 1. Redistributions of source code must retain the above copyright

# notice, this list of conditions and the following disclaimer.

# 2. Redistributions in binary form must reproduce the above copyright

# notice, this list of conditions and the following disclaimer in the

# documentation and/or other materials provided with the distribution.

# 3. All advertising materials mentioning features or use of this software

# must display the following acknowledgement:

# This product includes software developed by the Computer Systems

# Engineering Group at Lawrence Berkeley Laboratory.

# 4. Neither the name of the University nor of the Laboratory may be used

# to endorse or promote products derived from this software without

# specific prior written permission.

# THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS''


AND

# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,


THE

# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A


PARTICULAR PURPOSE

# ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE


LIABLE

# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR


CONSEQUENTIAL

# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE


GOODS

# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)

# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN


CONTRACT, STRICT

# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN


ANY WAY

# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF

# SUCH DAMAGE.

# $Header: /nfs/jade/vint/CVSROOT/ns-2/tcl/ex/wireless-mitf.tcl,v 1.2 2000/08/30 00:10:45


haoboy Exp $

# Simple demo script for the new APIs to support multi-interface for

# wireless node.

# Define options

# Please note:

# 1. you can still specify "channelType" in node-config right now:

# set val(chan) Channel/WirelessChannel

# $ns_ node-config ...

# -channelType $val(chan)

# ...

# But we recommend you to use node-config in the way shown in this script

# for your future simulations.

# 2. Because the ad-hoc routing agents do not support multiple interfaces


# currently, this script can't generate anything interesting if you config

# the interfaces of node 1 and 2 on different channels

# --Xuan Chen, USC/ISI, July 21, 2000

set val(chan) Channel/WirelessChannel ;#Channel Type

set val(prop) Propagation/TwoRayGround ;# radio-propagation model

set val(netif) Phy/WirelessPhy ;# network interface type

set val(mac) Mac/802_11 ;# MAC type

set val(ifq) Queue/DropTail/PriQueue ;# interface queue type

set val(ll) LL ;# link layer type

set val(ant) Antenna/OmniAntenna ;# antenna model

set val(ifqlen) 50 ;# max packet in ifq

set val(nn) 2 ;# number of mobilenodes

set val(rp) DSDV ;# routing protocol

#set val(rp) DSR ;# routing protocol

set val(x) 500

set val(y) 500

# Initialize Global Variables

set ns_ [new Simulator]

set tracefd [open wireless_mitf.tr w]

$ns_ trace-all $tracefd

set namtrace [open wireless_mitf.nam w]


$ns_ namtrace-all-wireless $namtrace $val(x) $val(y)

# set up topography object

set topo [new Topography]

$topo load_flatgrid $val(x) $val(y)

# Create God

create-god $val(nn)

# New API to config node:

# 1. Create channel (or multiple-channels);

# 2. Specify channel in node-config (instead of channelType);

# 3. Create nodes for simulations.

# Create channel #1 and #2

set chan_1_ [new $val(chan)]

set chan_2_ [new $val(chan)]

# Create node(0) "attached" to channel #1

# configure node, please note the change below.

$ns_ node-config -adhocRouting $val(rp) \

-llType $val(ll) \

-macType $val(mac) \
-ifqType $val(ifq) \

-ifqLen $val(ifqlen) \

-antType $val(ant) \

-propType $val(prop) \

-phyType $val(netif) \

-topoInstance $topo \

-agentTrace ON \

-routerTrace ON \

-macTrace ON \

-movementTrace OFF \

-channel $chan_1_

set node_(0) [$ns_ node]

# node_(1) can also be created with the same configuration, or with a different

# channel specified.

# Uncomment below two lines will create node_(1) with a different channel.

# $ns_ node-config \

# -channel $chan_2_

set node_(1) [$ns_ node]

$node_(0) random-motion 0

$node_(1) random-motion 0

for {set i 0} {$i < $val(nn)} {incr i} {


$ns_ initial_node_pos $node_($i) 20

# Provide initial (X,Y, for now Z=0) co-ordinates for mobilenodes

$node_(0) set X_ 5.0

$node_(0) set Y_ 2.0

$node_(0) set Z_ 0.0

$node_(1) set X_ 8.0

$node_(1) set Y_ 5.0

$node_(1) set Z_ 0.0

# Now produce some simple node movements

# Node_(1) starts to move towards node_(0)

$ns_ at 3.0 "$node_(1) setdest 50.0 40.0 25.0"

$ns_ at 3.0 "$node_(0) setdest 48.0 38.0 5.0"

# Node_(1) then starts to move away from node_(0)

$ns_ at 20.0 "$node_(1) setdest 490.0 480.0 30.0"

# Setup traffic flow between nodes


# TCP connections between node_(0) and node_(1)

set tcp [new Agent/TCP]

$tcp set class_ 2

set sink [new Agent/TCPSink]

$ns_ attach-agent $node_(0) $tcp

$ns_ attach-agent $node_(1) $sink

$ns_ connect $tcp $sink

set ftp [new Application/FTP]

$ftp attach-agent $tcp

$ns_ at 3.0 "$ftp start"

# Tell nodes when the simulation ends

for {set i 0} {$i < $val(nn) } {incr i} {

$ns_ at 30.0 "$node_($i) reset";

$ns_ at 30.0 "stop"

$ns_ at 30.01 "puts \"NS EXITING...\" ; $ns_ halt"

proc stop {} {

global ns_ tracefd

$ns_ flush-trace

close $tracefd

}
puts "Starting Simulation..."

$ns_ run

12. Performance evaluation

12 a:

#Link failure checking program


#Create a simulator object
set ns [new Simulator]

#Tell the simulator to use dynamic routing


$ns rtproto DV

#Open the nam trace file


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

#Define a 'finish' procedure


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

#Create seven nodes


for {set i 0} {$i < 7} {incr i} {
set n($i) [$ns node]
}

#Create links between the nodes


for {set i 0} {$i < 7} {incr i} {
$ns duplex-link $n($i) $n([expr ($i+1)%7]) 1Mb 10ms DropTail
}

#Create a UDP agent and attach it to node n(0)


set udp0 [new Agent/UDP]
$ns attach-agent $n(0) $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 n(3)


set null0 [new Agent/Null]
$ns attach-agent $n(3) $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.5 "$cbr0 start"
$ns rtmodel-at 1.0 down $n(1) $n(2)
$ns rtmodel-at 2.0 up $n(1) $n(2)
$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

12 b:

#performance evaluation(bandwidth settings) using xgraph

set ns [new Simulator]


$ns color 0 green

set f0 [open out0.tr w]

set f1 [open out1.tr w]

set f2 [open out2.tr w]

set f3 [open out3.nam w]

$ns namtrace-all $f3

set n0 [$ns node]

set n1 [$ns node]

set n2 [$ns node]

set n3 [$ns node]

set n4 [$ns node]

$ns duplex-link $n0 $n3 1Mb 100ms DropTail

$ns duplex-link $n1 $n3 1Mb 100ms DropTail

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

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

proc finish {} {

global ns f0 f1 f2 f3

$ns flush-trace

close $f0
close $f1

close $f2

close $f3

exec nam out3.nam &

exec xgraph out0.tr out1.tr out2.tr -geometry 800x400 &

exit 0

proc attach-expoo-traffic { node sink size burst idle rate } {

set ns [Simulator instance]

set source [new Agent/UDP]

$ns attach-agent $node $source

set traffic [new Application/Traffic/Exponential]

$traffic set packetSize_ $size

$traffic set burst_time_ $burst

$traffic set idle_time_ $idle

$traffic set rate_ $rate

$traffic attach-agent $source

$ns connect $source $sink

return $traffic

}
proc record {} {

global sink0 sink1 sink2 f0 f1 f2

set ns [Simulator instance]

set time 0.5

set bw0 [$sink0 set bytes_]

set bw1 [$sink1 set bytes_]

set bw2 [$sink2 set bytes_]

set now [$ns now]

puts $f0 "$now [expr $bw0/$time*8/1000000]"

puts $f1 "$now [expr $bw1/$time*8/1000000]"

puts $f2 "$now [expr $bw2/$time*8/1000000]"

$sink0 set bytes_ 0

$sink1 set bytes_ 0

$sink2 set bytes_ 0

$ns at [expr $now+$time] "record"

set sink0 [new Agent/LossMonitor]

set sink1 [new Agent/LossMonitor]


set sink2 [new Agent/LossMonitor]

$ns attach-agent $n4 $sink0

$ns attach-agent $n4 $sink1

$ns attach-agent $n4 $sink2

set source0 [attach-expoo-traffic $n0 $sink0 200 2s 1s 100k]

set source1 [attach-expoo-traffic $n1 $sink1 200 2s 1s 200k]

set source2 [attach-expoo-traffic $n2 $sink2 200 2s 1s 300k]

$ns at 0.0 "record"

$ns at 10.0 "$source0 start"

$ns at 10.0 "$source1 start"

$ns at 10.0 "$source2 start"

$ns at 50.0 "$source0 stop"

$ns at 50.0 "$source1 stop"

$ns at 50.0 "$source2 stop"

$ns at 60.0 "finish"


$ns run
13. Aim:

To study and understand the architecture and topology adopted in SASTRA infrastructure.

DESCRIPTION:

Central computing facility controls the IT infrastructure of over 2500 computer with latest
software and operating system.
It provides 24 hours access to 370MBPS internet level that is network though the computer

Novell window and unix servers super computer linux cluster and blade servers with
quadcore.Intel dell xenon processor,2.66GHz 8GB PCZ-3500.FDB DDR 2Ram 3AS 10K 3FFR
HDD with Raid providers a powerfil server architecture at SASTRA.

It user the router which provider comprehensive scalable and serve network routing which is
connected to bsnl and reliance 20Mbps.

The forti gate firewall connected two modem,forti analyzer,DITZ,Mz.The forti gate firewall has
Z features.

SASTRA has three layered switch which is connected to the buildings.This zone is called
militarized zone.

The unmanaged switches has no user configuration capability.

The forti range from 1-126 class A,class B from 128-191, class C from 192-223, class D from
224-239 , class E from 240-254. Private IP for each class

ADDITIONAL EXPERIMENTS

QUEUE MONITORING

set ns [new Simulator]

# Create a simple six node topology:

# s1 s3

# \ /

# 10Mb,2ms \ 1.5Mb,20ms / 10Mb,4ms

# r1 --------- r2

# 10Mb,3ms / \ 10Mb,5ms

# / \

# s2 s4
#

set node_(s1) [$ns node]

set node_(s2) [$ns node]

set node_(r1) [$ns node]

set node_(r2) [$ns node]

set node_(s3) [$ns node]

set node_(s4) [$ns node]

$ns duplex-link $node_(s1) $node_(r1) 10Mb 2ms DropTail

$ns duplex-link $node_(s2) $node_(r1) 10Mb 3ms DropTail

$ns duplex-link $node_(r1) $node_(r2) 1.5Mb 20ms RED

$ns queue-limit $node_(r1) $node_(r2) 25

$ns queue-limit $node_(r2) $node_(r1) 25

$ns duplex-link $node_(s3) $node_(r2) 10Mb 4ms DropTail

$ns duplex-link $node_(s4) $node_(r2) 10Mb 5ms DropTail

$ns duplex-link-op $node_(s1) $node_(r1) orient right-down

$ns duplex-link-op $node_(s2) $node_(r1) orient right-up

$ns duplex-link-op $node_(r1) $node_(r2) orient right

$ns duplex-link-op $node_(r1) $node_(r2) queuePos 0

$ns duplex-link-op $node_(r2) $node_(r1) queuePos 0

$ns duplex-link-op $node_(s3) $node_(r2) orient left-down

$ns duplex-link-op $node_(s4) $node_(r2) orient left-up


set tcp1 [$ns create-connection TCP/Reno $node_(s1) TCPSink $node_(s3) 0]

$tcp1 set window_ 15

set tcp2 [$ns create-connection TCP/Reno $node_(s2) TCPSink $node_(s3) 1]

$tcp2 set window_ 15

set ftp1 [$tcp1 attach-source FTP]

set ftp2 [$tcp2 attach-source FTP]

# Tracing a queue

set redq [[$ns link $node_(r1) $node_(r2)] queue]

set tchan_ [open all.q w]

$redq trace curq_

$redq trace ave_

$redq attach $tchan_

$ns at 0.0 "$ftp1 start"

$ns at 3.0 "$ftp2 start"

$ns at 10 "finish"

# Define 'finish' procedure (include post-simulation processes)

proc finish {} {

global tchan_

set awkCode {

if ($1 == "Q" && NF>2) {


print $2, $3 >> "temp.q";

set end $2

else if ($1 == "a" && NF>2)

print $2, $3 >> "temp.a";

set f [open temp.queue w]

puts $f "TitleText: red"

puts $f "Device: Postscript"

if { [info exists tchan_] } {

close $tchan_

exec rm -f temp.q temp.a

exec touch temp.a temp.q

exec awk $awkCode all.q

puts $f \"queue

exec cat temp.q >@ $f

puts $f \n\"ave_queue

exec cat temp.a >@ $f

close $f

exec xgraph -bb -tk -x time -y queue temp.queue &


exit 0

$ns run

MULTICASTING

set ns [new Simulator]

$ns multicast

set f [open out.tr w]

$ns trace-all $f

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

$ns color 1 red

# prune/graft packets

$ns color 30 purple

$ns color 31 green

set n0 [$ns node]

set n1 [$ns node]

set n2 [$ns node]

set n3 [$ns node]

# Use automatic layout

$ns duplex-link $n0 $n1 1.5Mb 10ms DropTail

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


$ns duplex-link $n1 $n3 1.5Mb 10ms DropTail

$ns duplex-link-op $n0 $n1 orient right

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

$ns duplex-link-op $n1 $n3 orient right-down

$ns duplex-link-op $n0 $n1 queuePos 0.5

set mrthandle [$ns mrtproto DM {}]

set cbr0 [new Application/Traffic/CBR]

set udp0 [new Agent/UDP]

$cbr0 attach-agent $udp0

$ns attach-agent $n1 $udp0

$udp0 set dst_ 0x8001

set cbr1 [new Application/Traffic/CBR]

set udp1 [new Agent/UDP]

$cbr1 attach-agent $udp1

$udp1 set dst_ 0x8002

$udp1 set class_ 1

$ns attach-agent $n3 $udp1

set rcvr [new Agent/LossMonitor]

#$ns attach-agent $n3 $rcvr

$ns at 1.2 "$n2 join-group $rcvr 0x8002"


$ns at 1.25 "$n2 leave-group $rcvr 0x8002"

$ns at 1.3 "$n2 join-group $rcvr 0x8002"

$ns at 1.35 "$n2 join-group $rcvr 0x8001"

$ns at 1.0 "$cbr0 start"

$ns at 1.1 "$cbr1 start"

$ns at 2.0 "finish"

proc finish {} {

global ns

$ns flush-trace

puts "running nam..."

exec nam out.nam &

exit 0

$ns run

CREATING NODES WITH DIFFERENT COLORS AND DIFFERENT SHAPES TO


DENOTE HUB, ROUTER AND SIMPLE NODE

#Create a simulator object

set ns [new Simulator]

#Define different colors for data flows (for NAM)


$ns color 1 Blue

$ns color 2 Red

$ns color 3 Black

#Open the NAM trace file

set nf [open out.nam w]

$ns namtrace-all $nf

#Define a 'finish' procedure

proc finish {} {

global ns nf

$ns flush-trace

#Close the NAM trace file

close $nf

#Execute NAM on the trace file

exec nam out.nam &

exit 0

#Create four nodes

set n0 [$ns node]

set n1 [$ns node]

set n2 [$ns node]

set n3 [$ns node]


$n3 shape "square"

$n3 color "black"

$n0 shape "square"

$n0 color "blue"

#Create links between the nodes

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

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

$ns duplex-link $n2 $n3 1.7Mb 20ms RED

$ns duplex-link-op $n0 $n2 color "blue"

$ns duplex-link-op $n0 $n2 label "cs-study"

$ns duplex-link-op $n1 $n2 color "green"

$ns duplex-link-op $n1 $n2 label "easylearning"

#Set Queue Size of link (n2-n3) to 10

$ns queue-limit $n2 $n3 10

#Give node position (for NAM)

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

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

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


#Monitor the queue for link (n2-n3). (for NAM)

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

#Setup a TCP connection

set tcp [new Agent/TCP]

$tcp set class_ 3

$ns attach-agent $n0 $tcp

set sink [new Agent/TCPSink]

$ns attach-agent $n3 $sink

$ns connect $tcp $sink

$tcp set fid_ 1

#Setup a FTP over TCP connection

set ftp [new Application/FTP]

$ftp attach-agent $tcp

$ftp set type_ FTP

#Setup a UDP connection

set udp [new Agent/UDP]

$ns attach-agent $n1 $udp

set null [new Agent/Null]

$ns attach-agent $n3 $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_ 1mb

$cbr set random_ false

#Schedule events for the CBR and FTP agents

$ns at 0.1 "$cbr start"

$ns at 1.0 "$ftp start"

$ns at 4.0 "$ftp stop"

$ns at 4.5 "$cbr stop"

#Detach tcp and sink agents (not really necessary)

$ns at 4.5 "$ns detach-agent $n0 $tcp ; $ns detach-agent $n3 $sink"

#Call the finish procedure after 5 seconds of simulation time

$ns at 5.0 "finish"

#Print CBR packet size and interval

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


puts "CBR interval = [$cbr set interval_]"

#Run the simulation

$ns run

Potrebbero piacerti anche