Friday, 22 July 2011

COMPUTER NETWORKS LAB MANUAL


1: Program  Time & Date Server

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package networklab;
import java.io.*;
import java.net.*;
import java.util.Date;


/**
 *
 * @author ARP
 */
public class TimeServer {
    public static final int PORT = 8086;
    ServerSocket ss;
    Socket s;

    public void processTimeRQST()throws IOException{
        ss=new ServerSocket(PORT);
        System.out.println("Started "+ss);
       
            try{
                while(true){
                    s=null;
                    s=ss.accept();
                    Writer out=new OutputStreamWriter(s.getOutputStream());
                    Date now=new Date();
                    out.write(now.toString());
                    out.flush();
                    s.close();
                }
            }
            catch(IOException ioe){
                System.out.println("error "+ioe.toString());
            }
            finally{
                if(s!=null)
                  s.close();
            }
    }

    public static void main(String arg[])throws IOException{
          TimeServer obTimeServer=new TimeServer();
          obTimeServer.processTimeRQST(); 
    }
}






/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package networklab;
import java.io.*;
import java.net.*;
import java.util.Date;


/**
 *
 * @author ARP
 */
public class TimeClient {
    InetAddress addr;
    Socket socket;

    public void getConnetion()throws IOException
    {
        addr=InetAddress.getByName(null);
        System.out.println("Address "+addr);
        socket=new Socket(addr,TimeServer.PORT);
    }

    public void sendTimeRQST()throws IOException{
    try{
        InputStream ipstrm=socket.getInputStream();
        StringBuffer time=new StringBuffer();
        int c;
        while((c=ipstrm.read())!=-1)
            time.append((char)c);
        String strTime=time.toString().trim();
        System.out.println("It is "+strTime+" At This System...");
       }
     catch(IOException ioe){
         System.out.println("error "+ioe.toString());
     }
     finally{
            socket.close();
     }
    }

 public static void main(String arg[])throws IOException
 {
   TimeClient obTimeClient=new TimeClient();
   obTimeClient.getConnetion();
   obTimeClient.sendTimeRQST();
  }
}




2. Echo Program
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package networklab;
import java.io.*;
import java.net.*;



/**
 *
 * @author ARP
 */
public class EchoServer {
    public static final int PORT = 8086;
    ServerSocket ss;
    Socket s;

    public void processEchoPkt()throws IOException{
        ss=new ServerSocket(PORT);
        System.out.println("Started "+ss);
        try{
                s=ss.accept();
                System.out.println("connection accepted "+s);
                BufferedReader bfr=new BufferedReader(new InputStreamReader(s.getInputStream()));
                PrintWriter out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(s.getOutputStream())),true);
                while(true){
                    String str=bfr.readLine();
                    if(str.equals("END"))
                        break;
                     System.out.println("Echoing "+str);
                     out.println(str);
                }
            }
            catch(IOException ioe){
                System.out.println("error "+ioe.toString());

            }
            finally{
                System.out.println("closing ...");
                s.close();
            }
    }

    public static void main(String arg[])throws IOException{
          EchoServer obEchoServer=new EchoServer();
          obEchoServer.processEchoPkt(); 
    }
}


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package networklab;
import java.io.*;
import java.net.*;


/**
 *
 * @author ARP
 */
public class EchoClient {
    InetAddress addr;
    Socket socket;

    public void getConnetion()throws IOException
    {
        addr=InetAddress.getByName(null);
        System.out.println("Address "+addr);
        socket=new Socket(addr,EchoServer.PORT);
    }

    public void sendEchoPkt()throws IOException{
    try{
        System.out.println("Sockt "+socket);
        BufferedReader bfr=new BufferedReader(new InputStreamReader(socket.getInputStream()));
        PrintWriter out= new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
        for(int i=0;i<10;i++)
        {
            out.println("no = "+i);
            String str=bfr.readLine();
            System.out.println(str);
        }
        out.println("END");
       }
     catch(IOException ioe){
         System.out.println("error "+ioe.toString());
     }
     finally{
            System.out.println("closing.....");
            socket.close();
     }

    }

 public static void main(String arg[])throws IOException
 {
   EchoClient obEchoClient=new EchoClient();
   obEchoClient.getConnetion();
   obEchoClient.sendEchoPkt();
  }
}
3. Chat Server - UDP
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package networklab;
import java.io.*;
import java.net.*;


/**
 *
 * @author ARP
 */
public class ChatServer {

    DatagramSocket ds;
    DatagramPacket dpSend,dpReceived;
    InetAddress inetHost;
    BufferedReader br;

    public void sendNreceivePkts(){
        try{
            ds=new DatagramSocket(1234);
            inetHost=InetAddress.getByName("localhost");
            br=new BufferedReader(new InputStreamReader(new DataInputStream(System.in)));
            while(ds!=null){
                dpReceived=new DatagramPacket(new byte[100],100);
                ds.receive(dpReceived);
                System.out.println("Request from the Client");
                String strRD=new String(dpReceived.getData());
                System.out.println(strRD.trim());
                if(strRD.equals("exit"))
                    break;
                System.out.println("Response to the Client");
                String strSD=br.readLine();
                byte byteData[]=strSD.getBytes();
                dpSend=new DatagramPacket(byteData,byteData.length,inetHost,1235);
                ds.send(dpSend);
                if(strSD.equals("exit"))
                    break;
            }
        }
        catch(Exception e){
            System.out.println("Error @ Server "+e.toString());
        }
    }
    public static void main(String arg[])throws IOException{
        ChatServer obCS=new ChatServer();
        obCS.sendNreceivePkts();
    }
}


Chat Client

package networklab;
import java.io.*;
import java.net.*;


public class ChatClient {
    DatagramSocket ds;
    DatagramPacket dpSend,dpReceived;
    InetAddress inetHost;
    BufferedReader br;

    public void sendNreceivePkts(){
        try{
            ds=new DatagramSocket(1235);
            inetHost=InetAddress.getByName("localhost");
            br=new BufferedReader(new InputStreamReader(new DataInputStream(System.in)));
            while(ds!=null){


                System.out.println("Request To The Server");
                String strSD=br.readLine();
                byte byteData[]=strSD.getBytes();
                dpSend=new DatagramPacket(byteData,byteData.length,inetHost,1234);
                ds.send(dpSend);
                if(strSD.equals("exit"))
                    break;


                dpReceived=new DatagramPacket(new byte[100],100);
                ds.receive(dpReceived);
                System.out.println("Response From the Server");
                String strRD=new String(dpReceived.getData());
                System.out.println(strRD.trim());
                if(strRD.equals("exit"))
                    break;


            }
        }
        catch(Exception e){
            System.out.println("Error @ Server "+e.toString());
        }
    }

    public static void main(String arg[]){
        ChatClient obCC=new ChatClient();
        obCC.sendNreceivePkts();
    }

}



4. Echo Using UDP
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package networklab;

import java.net.*;


public class EchoUDPServer {

    DatagramSocket ds;
    DatagramPacket dpSend,dpReceived;
    InetAddress inetHost;


 public void processPacket(){
       try{
            ds=new DatagramSocket(1235);
            inetHost=InetAddress.getByName("localhost");
            while(ds!=null){
                dpReceived=new DatagramPacket(new byte[50],50);
                ds.receive(dpReceived);
                String strR=new String(dpReceived.getData());
                System.out.println(strR.trim());
                if(strR.equals("exit"))
                    System.exit(0);

             }
       }
       catch(Exception e){
           System.out.println("Error @ server "+e.toString());
       }


 }

 public static void main(String arg[]){
     EchoUDPServer obEUS=new EchoUDPServer();
     obEUS.processPacket();
 }

}










/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package networklab;

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


/**
 *
 * @author ARP
 */
public class EchoUDPClient {

    DatagramSocket ds;
    DatagramPacket dpSend,dpReceived;
    InetAddress inetHost;
    BufferedReader br;


 public void processPacket(){
       try{
            ds=new DatagramSocket(1234);
            inetHost=InetAddress.getByName("localhost");
            br=new BufferedReader(new InputStreamReader(new DataInputStream(System.in)));
            System.out.println("Message to Server");
            while(ds!=null){
               
                String strS=br.readLine();
                byte byteData[]=strS.trim().getBytes();
                dpSend=new DatagramPacket(byteData,byteData.length,inetHost,1235);
                ds.send(dpSend);
                if(strS.equals("exit"))
                    break;
             }
       }
       catch(Exception e){
           System.out.println("Error @ client "+e.toString());
       }


 }

 public static void main(String arg[]){
     EchoUDPClient obEUC=new EchoUDPClient();
     obEUC.processPacket();
 }

}

5. Remote Procedure Call

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package networklab;
import java.io.*;
import java.rmi.*;
import java.rmi.server.*;

/**
 *
 * @author ARP
 */
public interface FileCopyIFCRPC {
 public String copyFile(String fn)throws RemoteException;
}


SERVER
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package networklab;

import java.io.*;
import java.rmi.*;
import java.net.*;
import java.rmi.server.*;

/**
 *
 * @author ARP
 */
public class FileCopyServerRPC extends UnicastRemoteObject implements FileCopyIFCRPC {
 FileCopyServerRPC() throws RemoteException{

 }
 public String copyFile(String fn){
     String data="";
     try{
         StringBuffer sb=new StringBuffer();
         File f=new File(fn);
         FileInputStream fin=new FileInputStream(f);
         InputStreamReader isr=new InputStreamReader(fin);
         BufferedReader br=new BufferedReader(isr);
         String strS1;
         while((strS1=br.readLine())!=null){
             sb.append(strS1);
             sb.append("\n");
         }
         br.close();
         data=sb.toString();
     }
     catch(Exception e){
         System.out.println("Error @ server "+e.toString());
     }
     return (data);
 }
 public static void main(String arg[])throws Exception{
     FileCopyServerRPC obFCSRPC=new FileCopyServerRPC();
     Naming.rebind("id", obFCSRPC);
     System.out.println("Registered File Copy with Registry");
 }
}


CLIENT

package networklab;
import java.rmi.*;
import java.io.*;


public class FileCopyClientRPC {
String strData,strSFN,strDFN;

    public void getFileNames()throws Exception{
        BufferedReader br=new BufferedReader(new InputStreamReader(new DataInputStream(System.in)));
        System.out.println("Enter the Source Filename");
        strSFN=br.readLine();
        System.out.println("Enter the Destination Filename");
        strDFN=br.readLine();
    }
    public void copyFile()throws Exception{
        FileCopyServerRPC fcs=(FileCopyServerRPC)Naming.lookup("id");
        strData=fcs.copyFile(strSFN);
        File f=new File(strDFN);
        FileOutputStream fos=new FileOutputStream(f);
        PrintStream ps=new PrintStream(fos);
        ps.println(strData);
        System.out.println(strDFN+" File Created");
    }

    public static void main(String arg[])throws Exception{
        FileCopyClientRPC obFCC=new FileCopyClientRPC();
        obFCC.getFileNames();
        obFCC.copyFile();
    }
}






6. Packet Capturing

Server

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package networklab;
import java.net.*;
import java.util.*;
import java.io.*;

/**
 *
 * @author ARP
 */
public class NetInterfServer {
    byte pkt[];
    DatagramSocket ds;
    DatagramPacket dp;

    public void capturePKT()throws IOException{
        pkt=new byte[1024];
        ds=new DatagramSocket(6000);
        dp=new DatagramPacket(pkt,pkt.length);
        ds.receive(dp);
        String strPKT=new String(dp.getData(),0,dp.getLength());
        System.out.println("Packe Received: "+strPKT);
    }
public static void main(String arg[])throws IOException{
    NetInterfServer obNetIFServer=new NetInterfServer();
    obNetIFServer.capturePKT();
}
}


















Client

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package networklab;
import java.net.*;
import java.lang.*;
import java.io.*;
import java.util.*;

/**
 *
 * @author ARP
 */
public class NetInterfClient {

    NetworkInterface nwif;
    Enumeration enumAddr;
    InetAddress inetAddr;
    DatagramSocket ds;
    DatagramPacket dp;
    DataInputStream dipstream;

    public void sendPKT()throws IOException{
        nwif=NetworkInterface.getByName("eth");
        enumAddr=nwif.getInetAddresses();
        inetAddr=(InetAddress)enumAddr.nextElement();
        System.out.println("Connection to :"+inetAddr);
        dipstream=new DataInputStream(System.in);
        System.out.println("Enter Packet contents...");
       // int intvalue=dipstream.read();
        String str="HelloWorld";
        byte pkt[]=new byte[1024];
        ds=new DatagramSocket(4000);
        pkt=str.getBytes();
        dp=new DatagramPacket(pkt,str.length(),inetAddr,6000);
        ds.send(dp);
    }
    public static void main(String arg[])throws IOException{
      NetInterfClient obNIFClient=new NetInterfClient();
      obNIFClient.sendPKT();
    }
}









7. Selective Repeat Algorithm

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package networklab;
import java.io.*;


/**
 *
 * @author ARP
 */
public class SelectiveRepeatAlg {
int intToPkt,intWinSize,intPktNo,intPCount;
 public SelectiveRepeatAlg()throws Exception{
     BufferedReader br=new BufferedReader(new InputStreamReader(new DataInputStream(System.in)));
     System.out.println("Enter the Window Size");
     intWinSize=Integer.parseInt(br.readLine());
     System.out.println("enter Total no. of packets ");
     intToPkt=Integer.parseInt(br.readLine());
     System.out.println("Do you want to kill any Packets: (y/n)");
     String strAns=br.readLine();
     if(strAns.equals("y"))
         System.out.println("Enter No.of Packets 2 kill");
     intPCount=1;
 }
 public void sRepeat(int pn)throws Exception{
     System.out.println("----------------------");
     System.out.println("Selective Repeats of Packets "+pn);
     System.out.println("----------------------");
     Thread.sleep(1000);
     System.out.println("Packet "+(pn)+("send==>"));
     Thread.sleep(1000);
     System.out.println("Packet "+(pn)+("received==>"));
     Thread.sleep(2000);
     System.out.println("ACK"+(pn)+" Received");
 }

 public int calculate(int cos,int pno){
     int n;
     if(cos>pno)
         n=intWinSize-(intPktNo%intWinSize);
     else
         n=intWinSize-intPktNo;

     return n;
 }

 public void trans()throws Exception{
  int intC,intCount=0;
  while(intPCount<intToPkt){
      if(intCount==intWinSize){ //to be checked intcount
         System.out.println("Next Session");
         intCount=0;
       }
 
      if(intPktNo==intPCount){
       System.out.println("Packet "+intPCount+" discard --->");
       Thread.sleep(2000);
       intPCount++;
       intC=calculate(intWinSize,intPktNo);
       System.out.println("Remaining Packet To be sent in th fashion "+intC);
       for(int j=0;j<=intC;j++){
           Thread.sleep(1000);
           System.out.println("Packet "+intPCount+"Sent==>");
           Thread.sleep(1000);
           System.out.println("\t\tPacket"+intPCount+" Received");
           Thread.sleep(2000);
           System.out.println("ACK"+intPCount+" Received");
           intPCount++;
           intCount=0;
       }
       sRepeat(intPktNo);
       Thread.sleep(2000);
       System.out.println("Next Session");
       intCount=0;
      }
      else{
          Thread.sleep(1000);
          System.out.println("Packet "+intPCount+"send==>" );
          Thread.sleep(1000);
          System.out.println("\t\tpacket"+intPCount+"Received");
          intPCount++;
      }
      intPCount++;
  }
 }
 public static void main(String arg[])throws Exception{
      SelectiveRepeatAlg obSRA=new SelectiveRepeatAlg();
      obSRA.trans();
  }
}















8. GoBackNProtocol

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package networklab;
import java.io.*;


/**
 *
 * @author ARP
 */
public class GoBackNProtocol {
int intToPkt,intWinSize,intPktNo,intPCount;

public GoBackNProtocol()throws Exception{
     BufferedReader br=new BufferedReader(new InputStreamReader(new DataInputStream(System.in)));
     System.out.println("Enter the Window Size");
     intWinSize=Integer.parseInt(br.readLine());
     System.out.println("enter Total no. of packets ");
     intToPkt=Integer.parseInt(br.readLine());
     if(intToPkt<intWinSize){
         System.out.println("\t\twindow size is greater than no.of packets can't do goback\n");
         System.exit(0);
     }
     System.out.println("\n\t\tdo you want to kill any packets (y/n):\t");
     String strAns=br.readLine();
     if(strAns.equals("y")){
         System.out.println("\n\t\tenter the paket number to kill: ");
         intPktNo=Integer.parseInt(br.readLine());
     }
     intPCount=1;
}

public int retrans(int pn,int pc,int cus)throws Exception{
    int s;
    System.out.println("\t\t===========================");
    System.out.println("\t\t\tGoBack To"+pn);
    System.out.println("\t\t===========================");
    System.out.println("Send\t\tReceived \t\tAcknowledgement");
    System.out.println("\t\t===========================");
    int k=pn;
    int l=intToPkt-pn;
    if(l<cus)
        s=cus;
    else
        s=l;
    for(int m=0;m<s;m++){
        Thread.sleep(1000);
        System.out.println("Packet"+(k)+" Send==>");
        Thread.sleep(1000);
        System.out.println("\t\tPacket"+(k)+"Received");
        Thread.sleep(2000);
        System.out.println("\t\t\t\tACK"+(k)+"Received");
        k++;
    }
    System.out.println("-----------End-----------");
    return k;
}

public int calculate(int cus,int pno){
    int n,x=0;
    if(pno<cus){
        n=cus-pno;
    }
    else{
        n=intToPkt-pno;
        if(n<=cus)
            n=pno; //to be checked pno
        else
            n=cus-(pno%cus);
    }
    return n;
}

public void trans()throws Exception{
    int intC,intCount=0;
    for(int i=0;i<intToPkt/intWinSize;i++){
        while(intPCount<=intToPkt){
            if(intCount==intWinSize){
                System.out.println("\tNext Session");
                intCount=0;
            }
            if(intPktNo==intPCount){
                System.out.println("Packet"+intPCount+" discard==>");
                Thread.sleep(2000);
                intPCount++;
                intC=calculate(intWinSize,intPktNo);
                System.out.println("Remaining packet to be sent in this session "+intC);
                System.out.println("Send\t\tReceived\t\tAcknowledgement");
                System.out.println("==========\t\t========\t\t=========");
                for(int j=0;j<intC;j++){
                    Thread.sleep(1000);
                    System.out.println("Packet "+intPCount+" send==>");
                    Thread.sleep(1000);
                    System.out.println("\t\tPacket"+intPCount+" Received");
                    Thread.sleep(2000);
                    System.out.println("\t\t\t\tACK"+intPCount+" Received");
                    intPCount++;
                    Thread.sleep(1000);
                    intCount=0;
                }
                intPCount=retrans(intPktNo,intPCount,intWinSize);
                Thread.sleep(2000);
                intCount=0;
            }
            else{
                System.out.println("Send\t\tReceived\t\tAcknowledgement");
                System.out.println("====\t\t========\t\t===============");
                Thread.sleep(1000);
                System.out.println("Packet "+intPCount+" send==>");
                Thread.sleep(1000);
                System.out.println("\t\tPacket "+intPCount+" Received");
                Thread.sleep(2000);
                System.out.println("\t\t\t\tACK "+intPCount+" Received");
                intPCount++;
                intCount=0;
                intCount++;
            }
        }
    }
}
public static void main(String arg[])throws Exception{
 GoBackNProtocol obGBNP=new GoBackNProtocol();
 obGBNP.trans();
}
}

































9. Shortest Path First Routing
#include<stdio.h>
#include<conio.h>
int  a[5][5],n,I,j;
void main(){
  void shortest();
  void getData();
  void display();
  clrscr();
  printf(“\n Program to find shortest path between two nodes”);
  getData();
  shortest();
  display();
  getch();
}
void  getData(){
clrscr();
printf(“\n Enter the number of host in the graph “);
scanf(“%d”,&n);
printf(“\n If there is no direct path\n Assign the highest value 1000”);
for(i=0;i<n;i++){
  a[i][j]=0;
  for(j=0;j<n;j++){
   if(i!=j){
                                                   printf(“\n Enter the distance between(%d,%d):”,i+1,j+1);
                                                 scanf(“%d”,&a[i][j]);
                                                 if(a[i][j]==0)
                                                     a[i][j]=1000;
     }
  }
   }
}

void shortest(){
int I,j,k;
for(k=0;k<n;k++){
     for(i=0;i<n;i++){
       for(j=0;j<n;j++){
           if(a[i][k]+a[k][j]<a[i][j])
                a[i][j]= a[i][k]+a[k][j];
        }
     }
  }
}
void display(){
int i,j;
for(i=0;i<n;i++){
  for(j=0;j<n;j++){
      if(i!=j) {
        printf(“\n Shortest path is (%d,%d)-- %d”,i+1,j+1,a[i][j]);
       }
  }
 }
getch();
}

10. Simple UDP (DNS System)

#include<stdio.h>
#include<error.h>
#include<netdb.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
int main(int argc,char *argv[1]){
  struct hostent  *hen;
   if(argc!=2){
     fprintf(stderr,”Enter the host name:\n”;
      exit(1);
   }
hen-gethostbyname(argv[1]);
if(hen==NULL){
   fprintf(stderr,”Host Not Found… \n”);
   }
printf(“Host Name :”%s\n”,hen->h_name);
printf(“IP Address: %s/n”,inet_ntea(*((struct in_addr *)hen->addr)));
}







No comments:

Post a Comment