Exemplo n.º 1
1
  public static void main(String[] args) throws IOException, InterruptedException {
    boolean running = true;
    // udp protocol over a socket.
    DatagramSocket socket = new DatagramSocket();

    while (running) {
      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

      String line = br.readLine();
      String[] inputs = line.split(" ");

      if (inputs.length < 2) {
        System.out.println("Usage: username command id");
        socket.close();
        return;
      }

      byte[] byteArr = (inputs[0] + " " + inputs[1] + " " + inputs[2]).getBytes();

      // send request
      byte[] buf = new byte[256];
      InetAddress address = InetAddress.getByName("localhost");
      DatagramPacket packet = new DatagramPacket(byteArr, byteArr.length, address, 4445);
      socket.send(packet);

      // get response
      packet = new DatagramPacket(buf, buf.length);
      socket.receive(packet);

      // display response
      String received = new String(packet.getData(), 0, packet.getLength());
      System.out.println("From server: " + received);
    }
    //   socket.close();
  }
Exemplo n.º 2
0
 // ---------------------------------------------------------
 // decide whether two host names (h1, h2) refer to same IP
 // ---------------------------------------------------------
 public static boolean sameHost(String h1, String h2) {
   try {
     String a1 = InetAddress.getByName(h1).getHostAddress();
     String a2 = InetAddress.getByName(h2).getHostAddress();
     if (a1.equals(a2)) return true;
   } catch (Exception e) {
     System.out.println(e);
   }
   return false;
 }
  public boolean open(String addr, int port, String bindAddr) {
    try {
      ssdpMultiSock = new MulticastSocket(null);
      ssdpMultiSock.setReuseAddress(true);
      InetSocketAddress bindSockAddr = new InetSocketAddress(port);
      ssdpMultiSock.bind(bindSockAddr);
      ssdpMultiGroup = new InetSocketAddress(InetAddress.getByName(addr), port);
      ssdpMultiIf = NetworkInterface.getByInetAddress(InetAddress.getByName(bindAddr));
      ssdpMultiSock.joinGroup(ssdpMultiGroup, ssdpMultiIf);
    } catch (Exception e) {
      Debug.warning(e);
      return false;
    }

    return true;
  }
Exemplo n.º 4
0
  public static void main(String args[]) throws Exception {
    // Making a text file
    String filename =
        "C:\\Users\\S.S. Mehta\\Desktop\\Codes\\ComputerNetworks\\CN_project\\CN_project\\test3.txt";
    makeTextFile(filename);

    // Reading the file and puttin it in buffer
    BufferedReader in = new BufferedReader(new FileReader(filename));
    char[] c1 = new char[PACKET_SIZE];
    c1 = readData(in);
    displayPacket(c1);

    // Step3 - making a socket , makeing a packet with inet address and sending it
    byte[] buffer = new byte[PACKET_SIZE];
    DatagramSocket skt = new DatagramSocket(PORT_NUMBER);
    DatagramPacket request = new DatagramPacket(buffer, buffer.length);

    // stop till you receive
    wait(skt, request);
    System.out.println("On server side \nrequest received from Slient");
    // making a packet with an inet address -
    InetAddress host = InetAddress.getByName("localhost");

    DatagramPacket reply = makePacket(c1, host);

    // Sending reply packet
    System.out.println("Sending reply packet to client");
    Thread.sleep(5000);
    skt.send(reply);

    // closing the socket
    skt.close();
  }
Exemplo n.º 5
0
  public static void main(String[] args) {
    int port = 5555;

    DatagramSocket socket;
    socket = null;
    try {
      socket = new DatagramSocket(port);
      socket.setBroadcast(true);
      socket.connect(InetAddress.getByName("255.255.255.255"), 5555);
    } catch (Exception e) {
      System.err.println("Connection failed. " + e.getMessage());
    }

    while (true) {
      String message = "hey";
      byte[] buf = message.getBytes();

      DatagramPacket packet = new DatagramPacket(buf, buf.length);
      try {
        socket.send(packet);
      } catch (Exception e) {
        System.err.println("Sending failed. " + e.getMessage());
      }
    }
  }
 Target(String host) {
   try {
     address = new InetSocketAddress(InetAddress.getByName(host), 80);
   } catch (IOException x) {
     failure = x;
   }
 }
Exemplo n.º 7
0
  /** 启动初始化,他确定网络中有多少个其它UDPBase和相关的信息 */
  public void initNet() throws UDPBaseException {
    try {
      mainThread = new SoleThread(this);

      localIP = InetAddress.getLocalHost().getHostAddress();
      int i = localIP.lastIndexOf('.');
      BROADCAST_ADDR = localIP.substring(0, i) + ".255";
      // System.out.println ("lip=="+localIP) ;
      // sendSocket = new DatagramSocket () ;
      // recvSocket = new MulticastSocket (RECV_PORT) ;
      recvSocket = new DatagramSocket(RECV_PORT);
      sendSocket = recvSocket;
      // recvAckSocket = new MulticastSocket (RECV_ACK_PORT) ;
      group = InetAddress.getByName(BROADCAST_ADDR);
      // recvSocket.joinGroup (group) ;
      // recvAckSocket.joinGroup (group) ;

      procMsgThd = new ProcMsgThd();
      procMsgThd.start();
      //
      mainThread.start();
    } catch (Exception e) {
      e.printStackTrace();
      throw new UDPBaseException("UDPBase init() error=\n" + e.toString());
    }
  }
  @Override
  public DatagramChannel bind(SocketAddress local) throws IOException {
    synchronized (readLock) {
      synchronized (writeLock) {
        synchronized (stateLock) {
          ensureOpen();
          if (localAddress != null) throw new AlreadyBoundException();
          InetSocketAddress isa;
          if (local == null) {
            // only Inet4Address allowed with IPv4 socket
            if (family == StandardProtocolFamily.INET) {
              isa = new InetSocketAddress(InetAddress.getByName("0.0.0.0"), 0);
            } else {
              isa = new InetSocketAddress(0);
            }
          } else {
            isa = Net.checkAddress(local);

            // only Inet4Address allowed with IPv4 socket
            if (family == StandardProtocolFamily.INET) {
              InetAddress addr = isa.getAddress();
              if (!(addr instanceof Inet4Address)) throw new UnsupportedAddressTypeException();
            }
          }
          SecurityManager sm = System.getSecurityManager();
          if (sm != null) {
            sm.checkListen(isa.getPort());
          }
          Net.bind(family, fd, isa.getAddress(), isa.getPort());
          localAddress = Net.localAddress(fd);
        }
      }
    }
    return this;
  }
Exemplo n.º 9
0
  /**
   * Konstruktor
   *
   * @param configFile Jmeno konfiguracniho souboru
   */
  public Server(String configFile) {
    setServerConfig(new ServerConfig(configFile));

    setPort(getServerConfig().getPort());
    try {
      setBindAddress(InetAddress.getByName(getServerConfig().getBindAddress()));
    } catch (UnknownHostException e) {
      System.err.println("Bind adresa neni platna!");
      System.exit(-1);
    }

    try {
      setServerSocket(new ServerSocket(getPort(), 0, getBindAddress()));
    } catch (IOException e) {
      System.err.println("Chyba startu ServerSocketu");
      System.exit(-1);
    }

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

    clients = new Hashtable<String, ServerThread>();
    boolean running = true;
    while (running) {
      try {
        accept();
      } catch (IOException e) {
        System.err.println("Chyba acceptu");
        running = false;
      }
    }
  }
Exemplo n.º 10
0
 // Check for an IP, since this seems to be safer to return then a plain name
 private String getIpIfPossible(String pHost) {
   try {
     InetAddress address = InetAddress.getByName(pHost);
     return address.getHostAddress();
   } catch (UnknownHostException e) {
     return pHost;
   }
 }
Exemplo n.º 11
0
  public InetAddress getExternalIpAddressHTTP(boolean v6) throws Exception {

    Map reply = executeHTTP(new HashMap(), v6);

    byte[] address = (byte[]) reply.get("source_ip_address");

    return (InetAddress.getByName(new String(address)));
  }
Exemplo n.º 12
0
  public InetAddress getExternalIpAddressUDP(InetAddress bind_ip, int bind_port, boolean v6)
      throws Exception {
    Map reply = executeUDP(new HashMap(), bind_ip, bind_port, v6);

    byte[] address = (byte[]) reply.get("source_ip_address");

    return (InetAddress.getByName(new String(address)));
  }
Exemplo n.º 13
0
  /**
   * Sends a leave message to the multicast group and leaves it. The <CODE>DiscoveryResponder</CODE>
   * leaves its multicast group. This method has no effect if the <CODE>DiscoveryResponder</CODE> is
   * <CODE>OFFLINE</CODE> or <CODE>STOPPING</CODE> or <CODE>STARTING</CODE>.
   */
  public void stop() {
    if (state == ONLINE) {
      changeState(STOPPING);
      // ------------------------
      // Stop corresponding thread
      // ------------------------

      responder.stopRequested = true;

      synchronized (responder.interrupted) {
        if (!responder.interrupted.booleanValue()) {
          responderThread.interrupt();
        }
      }

      // Fix for cases when the interrupt does not work (Windows NT)
      try {
        MulticastSocket ms = new MulticastSocket(multicastPort);

        // NPCTE fix for bugId 4499338, esc 0, 04 Sept 2001
        if (usrInet != null) {
          ms.setInterface(usrInet);

          if (logger.finerOn()) {
            logger.finer("stop ", "use the interface " + usrInet);
          }
        }
        // end of NPCTE fix for bugId 4499338

        InetAddress group = InetAddress.getByName(multicastGroup);
        ms.joinGroup(group);
        ms.send(new DatagramPacket(new byte[1], 1, group, multicastPort));
        ms.leaveGroup(group);
      } catch (Exception e) {
        if (logger.finerOn()) {
          logger.finer(
              "stop ",
              "Unexpected exception occurred trying to send empty message " + e.getMessage());
        }
      }

      // ------------------------
      // free 'remained' allocated resource
      // ------------------------
      responder = null;
      System.runFinalization();

      // ----------------
      // Update state
      // ----------------
      // changeState(OFFLINE) ;
    } else {
      if (logger.finerOn()) {
        logger.finer("stop ", "Responder is not ONLINE");
      }
    }
  }
Exemplo n.º 14
0
 public static InetAddress arrayToInetAddress(byte[] addr, int offset) {
   int[] i = byteToIntArray(addr, offset, 4);
   String s = i[0] + "." + i[1] + "." + i[2] + "." + i[3];
   try {
     return InetAddress.getByName(s);
   } catch (UnknownHostException e) {
     throw new RuntimeException("unknown host: " + s);
   }
 }
Exemplo n.º 15
0
 public byte[] getRAddr() {
   try {
     InetAddress addr = InetAddress.getByName(host);
     return addr.getAddress();
   } catch (UnknownHostException e) {
     System.err.println("NCCPConnection::getRAddr Don't know about host: ");
     return null;
   }
 }
Exemplo n.º 16
0
 public static String inaddrString(String s) {
   InetAddress address;
   try {
     address = InetAddress.getByName(s);
   } catch (UnknownHostException e) {
     return null;
   }
   return inaddrString(address);
 }
Exemplo n.º 17
0
 /**
  * Creates a SimpleResolver that will query the specified host
  *
  * @exception UnknownHostException Failure occurred while finding the host
  */
 public SimpleResolver(String hostname) throws UnknownHostException {
   if (hostname == null) {
     hostname = ResolverConfig.getCurrentConfig().server();
     if (hostname == null) hostname = defaultResolver;
   }
   InetAddress addr;
   if (hostname.equals("0")) addr = InetAddress.getLocalHost();
   else addr = InetAddress.getByName(hostname);
   address = new InetSocketAddress(addr, DEFAULT_PORT);
 }
Exemplo n.º 18
0
  /** Generic constructor for the name service interface */
  public LeetActive(String svc_host, int svc_port, int portNum) {

    try {
      nameServer = new DatagramSocket();
      nameServer.setSoTimeout(3000);
      nameServer.connect(InetAddress.getByName(svc_host), svc_port);
    } catch (Exception e) {
      System.err.println("LA " + e);
    }
    this.portNum = portNum;
    hostList = new ArrayList();
  }
Exemplo n.º 19
0
  public void Connect() throws IOException {
    try {
      InetAddress addr = InetAddress.getByName(server);
      Socket socket = new Socket(addr, port);

      in = new InputStreamReader(socket.getInputStream());
      out = new OutputStreamWriter(socket.getOutputStream());

      char c[] = new char[LINE_LENGTH];

      boolean authed = false;

      while (true) {
        if (in.read(c) > 0) {
          String msg = new String(c).trim();

          if (!authed) {
            if (msg.endsWith("No Ident response")) {

              System.out.println("...sending identity...");
              out.write(String.format("NICK %s\r\n", nickname));
              out.write(String.format("USER %s %s %s :s\r\n", nickname, host, server, realname));
              out.flush();

              authed = true;

              for (IRCAuthListener a : authListeners) {
                a.afterAuthentication(this);
              }
            }
          }

          if (msg.startsWith("PING")) {
            System.out.println("Sending pong...");
            out.write("PONG\r\n");
            out.flush();
          }

          for (IRCRawDataListener d : rawDataListeners) {
            d.processRawData(this, msg);
          }

          c = new char[LINE_LENGTH];
        } else {
          System.out.println("Oops, if you see this we just got kicked or connection timed out...");
          break;
        }
      }
    } catch (IOException ioe) {
      throw (ioe);
    }
  }
    protected void sendBeacon() {
      if (is_enabled) {

        try {
          byte[] bytes = encodeBeacon(true, tcp_port);

          control_socket.send(
              new DatagramPacket(
                  bytes, bytes.length, InetAddress.getByName("255.255.255.255"), CONTROL_PORT));

        } catch (Throwable e) {

          log("Failed to send beacon", e);
        }
      }
    }
Exemplo n.º 21
0
 public void setProperty(String prop, String value) {
   if (PORT.equals(prop)) {
     setPort(value);
   } else if (HANDLER.equals(prop)) {
     try {
       Class chC = Class.forName(value);
       con = (TcpConnectionHandler) chC.newInstance();
     } catch (Exception ex) {
       ex.printStackTrace();
     }
   } else if (INET.equals(prop)) {
     try {
       address = InetAddress.getByName(value);
     } catch (Exception ex) {
     }
   }
 }
Exemplo n.º 22
0
  private void checkLdapServer(ConfigGuideBean configGuideBean)
      throws PwmOperationalException, IOException {
    final Map<String, String> formData = configGuideBean.getFormData();
    final String host = formData.get(PARAM_LDAP_HOST);
    final int port = Integer.parseInt(formData.get(PARAM_LDAP_PORT));
    if (Boolean.parseBoolean(formData.get(PARAM_LDAP_SECURE))) {
      X509Utils.readRemoteCertificates(host, port);
    } else {
      InetAddress addr = InetAddress.getByName(host);
      SocketAddress sockaddr = new InetSocketAddress(addr, port);
      Socket sock = new Socket();

      // this method will block for the defined number of milliseconds
      int timeout = 2000;
      sock.connect(sockaddr, timeout);
    }
  }
Exemplo n.º 23
0
    @Override
    public void init(String keyspace) {
      Iterator<InetAddress> hostiter = hosts.iterator();
      while (hostiter.hasNext()) {
        try {
          // Query endpoint to ranges map and schemas from thrift
          InetAddress host = hostiter.next();
          Cassandra.Client client =
              createThriftClient(
                  host.getHostAddress(), rpcPort, this.user, this.passwd, this.transportFactory);

          setPartitioner(client.describe_partitioner());
          Token.TokenFactory tkFactory = getPartitioner().getTokenFactory();

          for (TokenRange tr : client.describe_ring(keyspace)) {
            Range<Token> range =
                new Range<>(
                    tkFactory.fromString(tr.start_token),
                    tkFactory.fromString(tr.end_token),
                    getPartitioner());
            for (String ep : tr.endpoints) {
              addRangeForEndpoint(range, InetAddress.getByName(ep));
            }
          }

          String query =
              String.format(
                  "SELECT * FROM %s.%s WHERE keyspace_name = '%s'",
                  Keyspace.SYSTEM_KS, SystemKeyspace.SCHEMA_COLUMNFAMILIES_CF, keyspace);
          CqlResult result =
              client.execute_cql3_query(
                  ByteBufferUtil.bytes(query), Compression.NONE, ConsistencyLevel.ONE);
          for (CqlRow row : result.rows) {
            CFMetaData metadata = CFMetaData.fromThriftCqlRow(row);
            knownCfs.put(metadata.cfName, metadata);
          }
          break;
        } catch (Exception e) {
          if (!hostiter.hasNext())
            throw new RuntimeException("Could not retrieve endpoint ranges: ", e);
        }
      }
    }
Exemplo n.º 24
0
  private void checkLdapServer(ConfigGuideBean configGuideBean)
      throws PwmOperationalException, IOException {
    final Map<String, String> formData = configGuideBean.getFormData();
    final String host = formData.get(PARAM_LDAP_HOST);
    final int port = Integer.parseInt(formData.get(PARAM_LDAP_PORT));

    { // socket test
      final InetAddress inetAddress = InetAddress.getByName(host);
      final SocketAddress socketAddress = new InetSocketAddress(inetAddress, port);
      final Socket socket = new Socket();

      final int timeout = 2000;
      socket.connect(socketAddress, timeout);
    }

    if (Boolean.parseBoolean(formData.get(PARAM_LDAP_SECURE))) {
      X509Utils.readRemoteCertificates(host, port);
    }
  }
Exemplo n.º 25
0
  protected String getHost(boolean v6, String v6_address, String v4_address) {
    if (v6) {

      try {
        return (InetAddress.getByName(v6_address).getHostAddress());

      } catch (UnknownHostException e) {

        try {
          return (DNSUtils.getIPV6ByName(v6_address).getHostAddress());

        } catch (UnknownHostException f) {

          return (v6_address);
        }
      }
    } else {

      return (v4_address);
    }
  }
  /**
   * Determine if a host is reachable by attempting to resolve the host name, and then attempting to
   * open a connection.
   *
   * @param hostName Name of the host to connect to.
   * @return {@code true} if a the host is reachable, {@code false} if the host name cannot be
   *     resolved, or if opening a connection to the host fails.
   */
  protected static boolean isHostReachable(String hostName) {
    try {
      // Assume host is unreachable if we can't get its dns entry without getting an exception
      //noinspection ResultOfMethodCallIgnored
      InetAddress.getByName(hostName);
    } catch (UnknownHostException e) {
      String message = Logging.getMessage("NetworkStatus.UnreachableTestHost", hostName);
      Logging.verbose(message);
      return false;
    } catch (Exception e) {
      String message = Logging.getMessage("NetworkStatus.ExceptionTestingHost", hostName);
      Logging.verbose(message);
      return false;
    }

    // Was able to get internet address, but host still might not be reachable because the address
    // might have been
    // cached earlier when it was available. So need to try something else.

    URLConnection connection = null;
    try {
      URL url = new URL("http://" + hostName);
      Proxy proxy = WWIO.configureProxy();
      if (proxy != null) connection = url.openConnection(proxy);
      else connection = url.openConnection();

      connection.setConnectTimeout(2000);
      connection.setReadTimeout(2000);
      String ct = connection.getContentType();
      if (ct != null) return true;
    } catch (IOException e) {
      String message = Logging.getMessage("NetworkStatus.ExceptionTestingHost", hostName);
      Logging.info(message);
    } finally {
      if (connection instanceof HttpURLConnection) ((HttpURLConnection) connection).disconnect();
    }

    return false;
  }
Exemplo n.º 27
0
  public static void main(String[] args) throws IOException {

    MulticastSocket socket = new MulticastSocket(4446);
    InetAddress address = InetAddress.getByName("230.0.0.1");
    socket.joinGroup(address);

    DatagramPacket packet;

    // get a few quotes
    for (int i = 0; i < 5; i++) {

      byte[] buf = new byte[256];
      packet = new DatagramPacket(buf, buf.length);
      socket.receive(packet);

      String received = new String(packet.getData(), 0, packet.getLength());
      System.out.println("Quote of the Moment: " + received);
    }

    socket.leaveGroup(address);
    socket.close();
  }
Exemplo n.º 28
0
  public void initGroup() throws UDPBaseException {
    try {
      mainThread = new SoleThread(this);

      sendSocket = new DatagramSocket();
      recvSocket = new MulticastSocket(RECV_PORT);
      // recvAckSocket = new MulticastSocket (RECV_ACK_PORT) ;
      group = InetAddress.getByName(GROUP_BROADCAST_ADDR);
      ((MulticastSocket) recvSocket).joinGroup(group);
      // recvAckSocket.joinGroup (group) ;
      localIP = InetAddress.getLocalHost().getHostAddress();

      procMsgThd = new ProcMsgThd();
      procMsgThd.start();
      //
      mainThread.start();

      bGroup = true;
    } catch (Exception e) {
      e.printStackTrace();
      throw new UDPBaseException("UDPBase init() error=\n" + e.toString());
    }
  }
Exemplo n.º 29
0
  public void initVirtual(String virtualip) throws UDPBaseException {
    if (virtualip == null) {
      virtualip = "vip:" + System.currentTimeMillis();
    }
    try {
      mainThread = new SoleThread(this);

      sendSocket = new DatagramSocket();
      recvSocket = new MulticastSocket(RECV_PORT);
      // recvAckSocket = new MulticastSocket (RECV_ACK_PORT) ;
      group = InetAddress.getByName(GROUP_BROADCAST_ADDR);
      ((MulticastSocket) recvSocket).joinGroup(group);
      // recvAckSocket.joinGroup (group) ;
      localIP = virtualip;

      procMsgThd = new ProcMsgThd();
      procMsgThd.start();
      //
      mainThread.start();
    } catch (Exception e) {
      e.printStackTrace();
      throw new UDPBaseException("UDPBase init() error=\n" + e.toString());
    }
  }
Exemplo n.º 30
0
  public void run() {

    do {
      try {
        BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
        File file = new File("time.txt");
        FileWriter fw = new FileWriter(file);
        Long start = 0l;
        Long end = 0l;
        BufferedWriter bw = new BufferedWriter(fw);
        System.out.println("Enter the preferred choice");
        System.out.println("1. REGISTER");
        System.out.println("2. LEAVE");
        System.out.println("3. SEARCH FOR RFC");
        System.out.println("4. KEEPALIVE");
        System.out.println("5. Do you want to EXIT");
        System.out.println("*********************************************");

        choice = Integer.parseInt(inFromUser.readLine());
        // System.out.println(" Client requesting for connection");
        clientSocket = new Socket("192.168.15.103", 6500);
        BufferedReader inFromServer =
            new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        PrintWriter outToServer =
            new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream()), true);

        // outToServer.println("Peer Requesting Connection");

        switch (choice) {
          case 4:
            outToServer.println(
                "KEEP ALIVE P2P-DI Cookieno "
                    + cookie
                    + " OS: "
                    + System.getProperty("os.name")
                    + " "
                    + "v"
                    + System.getProperty("os.version")
                    + " USER: "******"user.name"));
            System.out.println(inFromServer.readLine());
            System.out.println("*********************************************");
            break;
          case 1:
            try {
              // System.out.println("Case 1 entered"); // testing
              // statement
              System.out.println("Please enter your IP addres");
              ip = inFromUser.readLine();
              outToServer.println(
                  "REG P2P-DI/1.1 -1 Portno 6789 Hostname "
                      + ip
                      + " OS: "
                      + System.getProperty("os.name")
                      + " "
                      + "v"
                      + System.getProperty("os.version")
                      + " USER: "******"user.name"));
              cookie = Integer.parseInt(inFromServer.readLine());
              TTL = 7200;

              System.out.println(inFromServer.readLine());
              System.out.print("You are registered at time : ");
              ct.currenttime();
              System.out.println("Peer " + cookie); // peer cookie value
              System.out.println("TTL Value :" + TTL);
              System.out.println("*********************************************");

              break;
            } catch (Exception e) {
            }
          case 2:

            // System.out.println("Case 2 entered"); testing statement
            outToServer.println(
                "LEAVE P2P-DI Cookieno "
                    + cookie
                    + " OS: "
                    + System.getProperty("os.name")
                    + " "
                    + "v"
                    + System.getProperty("os.version")
                    + " USER: "******"user.name"));
            // System.out.println("I am in peer"); testing statement
            System.out.println(inFromServer.readLine());
            System.out.println("*********************************************");
            break;

          case 3:
            outToServer.println(
                "PQUERY P2P-DI Cookieno "
                    + cookie
                    + " Portno 6789"
                    + " OS: "
                    + System.getProperty("os.name")
                    + " "
                    + "v"
                    + System.getProperty("os.version")
                    + " USER: "******"user.name"));
            System.out.println("Which RFC number do you wish to have ?");
            reqrfc = Integer.parseInt(inFromUser.readLine());

            // System.out.println("Entered peer again");
            // outToServer.println("KEEP ALIVE cookieno "+cookie);

            String details = inFromServer.readLine();

            String[] parray = details.split(" ");
            int inactive = Integer.parseInt(parray[(parray.length - 1)]);
            // System.out.println(darray.length);
            if ((parray.length == 3) && (ip.equals(parray[1]))) {
              System.out.println("P2P-DI No Active Peers available");
              System.out.println("*********************************************");
            } else {
              System.out.println("****<POPULATING THE ACTIVE PEER LIST>****");
              System.out.println();
              System.out.println("The active peer list is as follows:");
              System.out.println();

              String[] darray = details.split(" ");

              // System.out.println("Array length"+darray.length);
              for (int i = 0; i < (darray.length - 2); i = i + 2) {

                acthostname[j] = darray[i + 1];
                System.out.println("Hostname :" + acthostname[j]);

                actportno[j] = Integer.parseInt(darray[i + 2]);
                System.out.println("Portno :" + actportno[j]);

                System.out.println("*****************************");
                j = j + 1;
              }

              System.out.println("Connecting to the active peers for its RFC Index");
              for (int x = 0; x < j; x++) {
                // System.out.println(ip);
                if (!(acthostname[x].equals(ip))) {
                  System.out.println("Connecting to " + acthostname[x]);

                  Socket peersocket = new Socket(acthostname[x], 6791); // implement
                  // a for
                  // loop

                  BufferedReader inFromPeer =
                      new BufferedReader(new InputStreamReader(peersocket.getInputStream()));
                  PrintWriter outToPeer =
                      new PrintWriter(new OutputStreamWriter(peersocket.getOutputStream()), true);

                  outToPeer.println("RFCIndex");
                  // System.out.println(inFromServer.readLine());
                  // int searchrfc=Integer.parseInt(inFromUser.readLine());
                  // outToServer.println(searchrfc);

                  String rfcindex = inFromPeer.readLine(); // tell server to
                  // send rfc in
                  // string
                  String rfcarray[] = rfcindex.split(" ");
                  //  System.out.println(rfcindex);
                  for (int i = 1; i < rfcarray.length; i = i + 4) {
                    trfcno[z] = Integer.parseInt(rfcarray[i]);
                    //	System.out.println("RFC number " + trfcno[z]);
                    trfctitle[z] = rfcarray[i + 1];
                    //	System.out.println("RFC Title " + trfctitle[z]);
                    tpeername[z] = rfcarray[i + 2];
                    //	System.out.println("Peer Ip Address " + tpeername[z]);
                    tpTTL[z] = Integer.parseInt(rfcarray[i + 3]);
                    //	System.out.println("TTL value :" + tpTTL[z]);

                    counter1 = counter1 + 1;

                    z = z + 1;
                  }
                  z = 0;
                  //         if(arraybound==0)
                  //         {
                  System.arraycopy(trfcno, 0, rfcno, counter2, trfcno.length);
                  System.arraycopy(trfctitle, 0, rfctitle, counter2, trfctitle.length);
                  System.arraycopy(tpeername, 0, peername, counter2, tpeername.length);
                  System.arraycopy(tpTTL, 0, pTTL, counter2, tpTTL.length);
                  z = 0;
                  counter2 = counter1;
                  counter1 = 0;
                  //         arraybound=arraybound+1;
                  //        }

                  System.out.println();
                  System.out.println();
                  System.out.println("*************************************************");
                  System.out.println("RFC Index received from the Peer");
                  //		System.out.println();
                  System.out.println("\n-----------------------------------------");
                  System.out.println("RFC Index System - Display RFC Idex");
                  System.out.println("-------------------------------------------");
                  System.out.format(
                      "%10s%15s%15s%10s", "RFC No", "RFC Title", "Peer Name", "TTL Value");
                  System.out.println();
                  // StudentNode current = top;
                  // while (current != null){
                  // Student read = current.getStudentNode();
                  for (int i = 0; i < 60; i++) {
                    System.out.format(
                        "%10s%15s%15s%10s",
                        " " + rfcno[i], rfctitle[i], peername[i], " " + pTTL[i]);
                    System.out.println();
                  }
                  // This will output with a set number of character spaces
                  // per field, giving the list a table-like quality
                  // }

                  peersocket.close();
                } // end of if

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

                  if (rfcno[i] == reqrfc) {
                    String taddress = InetAddress.getByName(peername[i]).toString();
                    String[] taddr = taddress.split("/");
                    InetAddress tproperaddress = InetAddress.getByName(taddr[1]);
                    //	System.out.println("Inetaddress" + tproperaddress);

                    Socket peersocket1 = new Socket(tproperaddress, 6791); // implement
                    // a
                    // for
                    // loop
                    System.out.println("The connection to the Active Peer is establshed");
                    BufferedReader inFromP2P =
                        new BufferedReader(new InputStreamReader(peersocket1.getInputStream()));
                    PrintWriter outToP2P =
                        new PrintWriter(
                            new OutputStreamWriter(peersocket1.getOutputStream()), true);

                    System.out.println("Requested the RFC to the Active Peer Server");

                    start = System.currentTimeMillis();

                    outToP2P.println("GETRFC " + reqrfc);

                    // Socket socket = ;

                    try {

                      // Socket socket = null;
                      InputStream is = null;
                      FileOutputStream fos = null;
                      BufferedOutputStream bos = null;
                      int bufferSize = 0;

                      try {
                        is = peersocket1.getInputStream();

                        bufferSize = 64;
                        // System.out.println("Buffer size: " + bufferSize);
                      } catch (IOException ex) {
                        System.out.println("Can't get socket input stream. ");
                      }

                      try {
                        fos = new FileOutputStream("E:\\rfc" + reqrfc + "copy.txt");
                        bos = new BufferedOutputStream(fos);

                      } catch (FileNotFoundException ex) {
                        System.out.println("File not found. ");
                      }

                      byte[] bytes = new byte[bufferSize];

                      int count;

                      while ((count = is.read(bytes)) > 0) {
                        //	System.out.println(count);
                        bos.write(bytes, 0, count);
                      }
                      System.out.println("P2P-DI 200 OK The RFC is copied");
                      end = System.currentTimeMillis();
                      System.out.println(
                          "Total Time to download file   " + (end - start) + " milliseconds");

                      bos.flush();

                      bos.close();
                      is.close();
                      peersocket1.close();
                      break;

                    } catch (SocketException e) {
                      System.out.println("Socket exception");
                    }

                  } // end of if
                  else {
                    //  	System.out.println("No Peer with the required RFC could be found");

                  }
                  clientSocket.close();
                  //	System.out.println("Connection closed");
                  bw.close();
                  fw.close();
                } // end of inner for
              } // end of outer for
              System.out.println("Connection closed");
            } // end of switch
        } // end of else which checks the inactive conditions
      } // end of try
      catch (IOException ioe) {
        System.out.println("IOException on socket listen: " + ioe);
        ioe.printStackTrace();
      }

    } // end of do
    while (choice != 5);
  } // end of run