skip to main | skip to sidebar

Java Programs and Examples with Output

Pages

▼
 
  • RSS
  • Twitter
Showing posts with label Java Network Example. Show all posts
Showing posts with label Java Network Example. Show all posts
Wednesday, October 24, 2012

Unicast Messaging in Java

Posted by Raju Gupta at 7:00 AM – 0 comments
 
Unicast messaging is used for all network processes in which a private or unique resource is requested.

import java.awt.*;
import java.awt.event.*;
import java.net.*;
import javax.swing.JFrame;

public class Unicast extends JFrame implements ActionListener{
 Label entermsgl,receivedmsgl,sentmsgl,toportl;
 TextField entermsg,toport;
 TextArea receivedmsg,sentmsg;
 Button send,exit;
 int myport;
 DatagramSocket ds;
 DatagramPacket dp;
 Unicast(){
  new InputDialog(this);
 }
 public void initialise(){
  setTitle("Unicast --Port:"+myport);
  setVisible(true);
  setSize(600,400);
  entermsgl=new Label("Enter Message:");
  receivedmsgl=new Label("Received Messages:");
  sentmsgl=new Label("Sent Messages:");
  toportl=new Label("To");
  toport=new TextField();
  entermsg=new TextField();
  receivedmsg=new TextArea();
  sentmsg=new TextArea();
  send=new Button("Send");
  exit=new Button("Exit");
  setLayout(null);
  add(entermsgl);
  entermsgl.setBounds(25,25,100,25);
  add(receivedmsgl);
  receivedmsgl.setBounds(25,70,150,25);
  add(sentmsgl);
  sentmsgl.setBounds(25,185,150,25);
  add(toportl);
  toportl.setBounds(350,25,25,25);
  add(toport);
  toport.setBounds(380,25,70,25);
  add(entermsg);
  entermsg.setBounds(130,25,200,25);
  add(receivedmsg);
  receivedmsg.setBounds(180,70,370,100);
  add(sentmsg);
  sentmsg.setBounds(180,185,370,100);
  add(send);
  send.setBounds(470,25,100,25);
  add(exit);
  exit.setBounds(250,300,100,25);
  try{
   ds=new DatagramSocket(myport);
  }catch(Exception e){
   System.out.println(e);
  }
  send.addActionListener(this);
  exit.addActionListener(this);
  new Receive();
 }
 class Receive extends Thread{
  Receive(){
   start();
  }
  public void run(){
   while(true){
    try{
     byte b[]=new byte[100];
     dp=new DatagramPacket(b,b.length);
     ds.receive(dp);
     receivedmsg.append("From "+dp.getPort()+": "+new String(dp.getData(),0,dp.getLength())+"n");
    }catch(Exception e){
     
    }
   }
   
  }
 }
 public void actionPerformed(ActionEvent ae){
  if(ae.getSource()==send){
   byte b[]=entermsg.getText().getBytes();
   try{
    int port=Integer.parseInt(toport.getText());
    if(port<1024 || port>65536){
      toport.setText("");
      return;
    }
    dp=new DatagramPacket(b,b.length,InetAddress.getLocalHost(),port);
    ds.send(dp);
    sentmsg.append("To "+port+": "+entermsg.getText()+"n");
   }catch(NumberFormatException nfe){
    toport.setText("");
   }catch(Exception e){
    
   }
  }
  else{
   System.exit(0);
  }
 }
 public static void main(String args[]){
  new Unicast();
 }

}


class InputDialog extends Dialog implements ActionListener{
 Button ok=new Button("Ok");
 Button cancel=new Button("Cancel");
 TextField tf=new TextField();
 Label l=new Label("Enter the port number:");
 Unicast parent;
 InputDialog(Unicast f){
  super(f,"Unicast - Port number");
  parent=f;
  setVisible(true);
  setSize(400,200);
  setLayout(null);
  add(l);
  l.setBounds(25,50,200,25);
  add(tf);
  tf.setBounds(225,50,100,25);
  add(ok);
  ok.setBounds(100,100,100,25);
  add(cancel);
  cancel.setBounds(220,100,100,25);
  ok.addActionListener(this);
  cancel.addActionListener(this);
 } 
 public void actionPerformed(ActionEvent ae){
  if(ae.getSource()==ok){
   try{
    int n=Integer.parseInt(tf.getText());
    if(n>1023 && n<65536){
     parent.myport=n;
     parent.initialise();
     this.dispose();
    }
    else{
     tf.setText("");
     tf.requestFocus();
    }
   }catch(NumberFormatException nfe){
    tf.setText("");
    tf.requestFocus();
   }
  }
  else if(ae.getSource()==cancel){
   System.exit(0);
  }
  
 }
}

[ Read More ]
Read more...

Chat Client and Chat Server

Posted by Raju Gupta at 2:26 AM – 0 comments
 
Communication between the clients from Server

//Chat Server:-

import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;

public class ChatServer extends Frame implements ActionListener{
 Label listOfClients;
 List clientName;
 Button exit;
 Panel p1,p2;
 ServerSocket ss;
 Clients clients[];
 int n;
 boolean sendOk=true;
 boolean update=false;

 ChatServer(){
  super("ChatServer");
  setSize(400,300);
  setVisible(true);
  clientName=new List();
  listOfClients=new Label("List of Clients");
  exit=new Button("Exit");
  p1=new Panel();
  p2=new Panel();
  p1.setLayout(new FlowLayout());
  p2.setLayout(new FlowLayout());
  setLayout(new GridLayout(2,1));
  add(p1);
  add(p2);
  p1.add(listOfClients);
  p1.add(clientName);
  p2.add(exit);
  exit.addActionListener(this);
  try{
   ss=new ServerSocket(2500);
  }catch(Exception e){
  }
  clients=new Clients[50];
  n=0;
  new CheckNewClients().start();
  new UpdateClients().start();
  
 }
 public void actionPerformed(ActionEvent ae){
  System.exit(0);
 }
 public static void main(String args[]){
  new ChatServer();
 }
 class Clients extends Thread{
  Socket s;
  BufferedReader br;
  PrintWriter pw;
  String name="Client ";
  int i;
  boolean alive;
  public void run(){
   try{
    while(true){
     String temp=br.readLine();
     if(temp.equals("shutdown")){
      for(int x=0;x<clientName.getItemCount();x++)
       if(clientName.getItem(x).equals(name)){
        clientName.remove(x);
        break;
       }
      alive=false;
      update=true;
      break;
     }
     else if(temp.equals("msg")){
      String client=br.readLine(); 
      String msg=br.readLine();
      int x;
      for(x=0;x<n;x++)
       if(clients[x].name.equals(client))
        break;
      while(!sendOk);
      sendOk=false;
      clients[x].pw.println("msg");
      clients[x].pw.println(name+" : "+msg);
      sendOk=true;
     }
    }
   }catch(Exception e){ 
    for(int x=0;x<clientName.getItemCount();x++)
     if(clientName.getItem(x).equals(name)){
      clientName.remove(x);
      break;
     }
    alive=false;
    update=true;
   }
  }
 }
 class CheckNewClients extends Thread{
  public void run(){
   while(true){
    clients[n]=new Clients();
    try{
     clients[n].s=ss.accept(); 
     clients[n].br=new BufferedReader(new InputStreamReader(clients[n].s.getInputStream()));
     clients[n].pw=new PrintWriter(clients[n].s.getOutputStream(),true);
     clients[n].i=n;
     clients[n].name+=n;
     clients[n].alive=true;
     clientName.add(clients[n].name);
     clients[n].pw.println(clients[n].name);
     clients[n].start(); 
     update=true;
    }catch(Exception e){
     System.out.println(e);
    }
    n++;
   }
  }
 }
 class UpdateClients extends Thread{
  public void run(){
   while(true){
    while(!update);
    for(int i=0;i<n;i++){
     int count=clientName.getItemCount();
     if(!clients[i].alive)
      continue;
     try{
      while(!sendOk);
      sendOk=false;
      clients[i].pw.println("update");
      clients[i].pw.println(count-1);
      for(int x=0;x<count;x++)
       if(!clientName.getItem(x).equals(clients[i].name))
        clients[i].pw.println(clientName.getItem(x));
      sendOk=true;
     }catch(Exception e){
      System.out.println(e);
     }
    }
    update=false;
   }
  }
 }
}


//Chat Client:-

import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;

public class ChatClient extends Frame implements ActionListener{
 Label enterMessage,to,receivedMessages,sentMessages;
 TextField enterMessaget;
 TextArea receivedMessagest,sentMessagest;
 Button send,exit;
 Choice clientName;
 Panel p1,p2,p3,p4;
 Socket s;
 PrintWriter pw;
 BufferedReader br;

 ChatClient(){
  super("ChatClient");
  setVisible(true);
  setSize(500,300);
  enterMessage=new Label("Enter Message");
  to=new Label("To");
  receivedMessages=new Label("Received Messages");
  sentMessages=new Label("Sent Messages");
  enterMessaget=new TextField();
  receivedMessagest=new TextArea("",20,5,TextArea.SCROLLBARS_VERTICAL_ONLY);
  sentMessagest=new TextArea();
  clientName=new Choice();
  send=new Button("Send");
  exit=new Button("Exit");
  p1=new Panel();
  p2=new Panel();
  p3=new Panel();
  p4=new Panel();
  setLayout(new GridLayout(4,1));
  p1.setLayout(null);
  p2.setLayout(new GridLayout(1,2));
  p3.setLayout(new GridLayout(1,2));
  p4.setLayout(new FlowLayout());
  p1.add(enterMessage);
  enterMessage.setBounds(10,10,100,25);
  p1.add(enterMessaget);
  enterMessaget.setBounds(110,10,100,25);
  p1.add(to);
  to.setBounds(220,10,30,25);
  p1.add(clientName);
  clientName.setBounds(260,10,100,25);
  p1.add(send);
  send.setBounds(370,10,100,25);
  p2.add(receivedMessages);
  p2.add(receivedMessagest);
  p3.add(sentMessages);
  p3.add(sentMessagest);
  p4.add(exit);
  add(p1);
  add(p2);
  add(p3);
  add(p4);
  exit.addActionListener(this); 
  send.addActionListener(this);
  try{
   s=new Socket("localhost",2500);
   br=new BufferedReader(new InputStreamReader(s.getInputStream()));
   pw=new PrintWriter(s.getOutputStream(),true);
   setTitle(br.readLine());
  }catch(Exception e){
   System.out.println("Exception: Problem establishing connectionn"+e);
  }
  new ReceiveMsg().start();
 }
 public static void main(String args[]){
  new ChatClient();
 }
 public void actionPerformed(ActionEvent ae){
  if(ae.getSource()==send){
   try{
    pw.println("msg");
    String client=clientName.getSelectedItem();
    String msg=enterMessaget.getText();
    pw.println(client);
    pw.println(msg);
    sentMessagest.append(client+" : "+msg+"n");
   }catch(Exception e){
   }
   
  }
  else if(ae.getSource()==exit){
   try{
    pw.println("shutdown");
   }catch(Exception e){
   }
   System.exit(0);
  }
 }
 class ReceiveMsg extends Thread{
  public void run(){
   while(true){
    try{
     String temp=br.readLine();
     if(temp.equals("update")){
      receiveUpdate();     
     }
     else if(temp.equals("msg")){
      receiveMsg();
     }
    }catch(Exception e){
    }
   }    
  }
  public void receiveMsg(){
   try{
    receivedMessagest.append(br.readLine()+"n");
   }catch(Exception e){
   }
  }
  public void receiveUpdate(){
   try{
    int n=Integer.parseInt(br.readLine());
    clientName.removeAll();
    for(int i=0;i<n;i++)
     clientName.add(br.readLine());      
   }catch(Exception e){
   }
  }
 }
 class sendUpdate extends Thread{
  public void run(){
   while(true){
    pw.println("alive");
    try{
     sleep(10000);
    }catch(Exception e){
    }
   }
  }
 }
}

[ Read More ]
Read more...
Tuesday, October 23, 2012

MultiCast Messaging in Java

Posted by Raju Gupta at 9:30 PM – 0 comments
 
Sending the file or message to a set of clients or group of clients

import java.awt.*;
import java.awt.event.*;
import java.net.*;
import javax.swing.JFrame;

public class Multicast extends JFrame implements ActionListener,Runnable{
 Label entermsgl,receivedmsgl,sentmsgl;
 TextField entermsg;
 TextArea receivedmsg,sentmsg;
 Button Multicast,exit;
 int myport;
 MulticastSocket ms_send,ms_receive;
 DatagramPacket dp;
 InetAddress address;
 Thread t;
 Multicast(){
  initialise();
 }
 public void initialise(){
  setTitle("Multicast ");
  setVisible(true);
  setSize(600,400);
  entermsgl=new Label("Enter Message:");
  receivedmsgl=new Label("Received Messages:");
  sentmsgl=new Label("Sent Messages:");
  entermsg=new TextField();
  receivedmsg=new TextArea();
  sentmsg=new TextArea();
  Multicast=new Button("Multicast");
  exit=new Button("Exit");
  setLayout(null);
  add(entermsgl);
  entermsgl.setBounds(25,25,100,25);
  add(receivedmsgl);
  receivedmsgl.setBounds(25,70,150,25);
  add(sentmsgl);
  sentmsgl.setBounds(25,185,150,25);
  add(entermsg);
  entermsg.setBounds(130,25,200,25);
  add(receivedmsg);
  receivedmsg.setBounds(180,70,370,100);
  add(sentmsg);
  sentmsg.setBounds(180,185,370,100);
  add(Multicast);
  Multicast.setBounds(470,25,100,25);
  add(exit);
  exit.setBounds(250,300,100,25);
  try{
   address=InetAddress.getByName("230.150.150.15");
   ms_send=new MulticastSocket();
   ms_receive=new MulticastSocket(2001);
   ms_receive.joinGroup(address);
  }catch(Exception e){
   System.out.println(e);
  }
  Multicast.addActionListener(this);
  exit.addActionListener(this);
  t=new Thread(this);
  t.start();
 }
 //class Receive extends Thread{
 // Receive(){
  // start();
  //}
  public void run(){
   while(true){
    System.out.println("1");
    try{
     DatagramPacket dp1;
     byte b[]=new byte[100];
     System.out.println("2");
     dp1=new DatagramPacket(b,b.length);
     ms_receive.receive(dp1);
     System.out.println("3");
     receivedmsg.append("From "+dp1.getAddress()+" "+dp1.getPort()+": "+new String(dp1.getData(),0,dp1.getLength())+"\n");
     repaint();
    }catch(Exception e){
     System.out.println(e);
    }
   }
   
  }
 //}
 public void actionPerformed(ActionEvent ae){
  if(ae.getSource()==Multicast){
   byte b[]=entermsg.getText().getBytes();
   try{
    dp=new DatagramPacket(b,b.length,address,2001);
    ms_send.send(dp,(byte)1);
    sentmsg.append(ms_send.getLocalAddress()+" port:"+ms_send.getLocalPort()+": "+entermsg.getText()+"\n");
   }catch(NumberFormatException nfe){
   }catch(Exception e){
    System.out.println(e);
   }
  }
  else{
   System.exit(0);
  }
 }
 public static void main(String args[]){
  new Multicast();
 }

}


[ Read More ]
Read more...
Wednesday, October 17, 2012

TCP Client Server communication using Java

Posted by Raju Gupta at 3:00 PM – 0 comments
 
The Transmission Control Protocol (TCP) provides reliable, ordered delivery of a stream of octets from a program on one computer to another program on another computer. Here it is illustrated by sending text data from one system to another. BufferedReader class is used to process data at the client and server side.

//Client Side:
------------------------------------------------------------------------------------------------------
import java.io.*;
import java.net.*;

class TCPClient
{
 public static void main(String argv[]) throws Exception
 {
  String sentence;
  String modifiedSentence;

  BufferedReader inFromUser = new BufferedReader( new InputStreamReader(System.in));
  Socket clientSocket = new Socket("localhost", 6780);
  //6780 is the port used for TCP communication

  DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());

  BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
  System.out.print(" file name : ");
  sentence = inFromUser.readLine();
  System.out.println("ffff --> "+sentence);
  outToServer.writeBytes(sentence+'\n');
  modifiedSentence = inFromServer.readLine();
  System.out.println("FROM SERVER: " + modifiedSentence);

  FileOutputStream f = new FileOutputStream("copy of "+sentence);
  DataOutputStream d = new DataOutputStream(f);
  byte fd[] = new byte[1024];
  fd = modifiedSentence.getBytes();
  d.write(fd);

  clientSocket.close();
 }
}

//Server Side:
-------------------------------------------------------------------------------------------------------
import java.io.*;
import java.net.*;

class TCPServer
{
 public static void main(String argv[]) throws Exception
 {
  String clientSentence;
  String capitalizedSentence;
  ServerSocket welcomeSocket = new ServerSocket(6780);

  while(true)
  {
   Socket connectionSocket = welcomeSocket.accept();
   BufferedReader inFromClient =

     new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));

   DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());

   clientSentence = inFromClient.readLine();

   System.out.println("Received: " + clientSentence);

   BufferedReader br = new BufferedReader(new FileReader(clientSentence));
   String filecontent="";
   //File content is cleared
   filecontent = br.readLine();

   System.out.println("file : "+filecontent);

   outToClient.writeBytes(filecontent+'\n');
  }
 }
}


[ Read More ]
Read more...

UDP Client Server Communication using Java

Posted by Raju Gupta at 12:00 PM – 1 comments
 

UDP uses a simple transmission model without implicit handshaking dialogues for providing reliability, ordering, or data integrity. Here this is illustrated using Java, by sending data (text) from one system to another using UDP, without connection establishment.

//Client Side:
------------------------------------------------------------------------------------------------------

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

class UDPClient
{
   public static void main(String args[]) throws Exception
   {
      BufferedReader inFromUser =
         new BufferedReader(new InputStreamReader(System.in));

      DatagramSocket clientSocket = new DatagramSocket();
 //Client Socket is created

      InetAddress IPAddress = InetAddress.getByName("localhost");
 //Gets the IP Address 

      byte[] sendData = new byte[1024];
      byte[] receiveData = new byte[1024];

      String sentence = inFromUser.readLine();

      sendData = sentence.getBytes();
 //sends data

      DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
      clientSocket.send(sendPacket);

      DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
      clientSocket.receive(receivePacket);

      String modifiedSentence = new String(receivePacket.getData());
      System.out.println("FROM SERVER:" + modifiedSentence);
      clientSocket.close();
   }
}

//Server Side:
-------------------------------------------------------------------------------------------------------

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

class UDPServer
{
   public static void main(String args[]) throws Exception
      {
         DatagramSocket serverSocket = new DatagramSocket(9876);
  //Server Socekt Created

            byte[] receiveData = new byte[1024];
            byte[] sendData = new byte[1024];
            while(true)
               {
                  DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
                  serverSocket.receive(receivePacket);
                  String sentence = new String( receivePacket.getData());
                  System.out.println("RECEIVED: " + sentence);

                  InetAddress IPAddress = receivePacket.getAddress();
                  int port = receivePacket.getPort();

                  String capitalizedSentence = sentence.toUpperCase();
   //Change sentence to Capital letter
                  sendData = capitalizedSentence.getBytes();

                  DatagramPacket sendPacket =
                  new DatagramPacket(sendData, sendData.length, IPAddress, port);
                  serverSocket.send(sendPacket);
   //Send Capitalized data back to client
               }
      }
}


[ Read More ]
Read more...

Java Token Ring Application

Posted by Raju Gupta at 6:00 AM – 0 comments
 

Token ring local area network (LAN) technology is a protocol which resides at the data link layer (DLL) of the OSI model. It uses a special three-byte frame called a token that travels around the ring. Token-possession grants the possessor permission to transmit on the medium. Token ring frames travel completely around the loop.
This is a simple Java program that illustrates the working of a token ring.

import java.io.*;
import java.lang.*;

class Tring {
 public static void main(String args[]) throws Throwable {
  DataInputStream dis = new DataInputStream(System.in);
  System.out.println("Enter the num of nodes:");
  int n = Integer.parseInt(dis.readLine());
  // Decides the number of nodes forming the ring
  int token = 0;
  int ch = 1;
  for (int i = 0; i < n; i++)
   System.out.print(" " + i);
  System.out.println(" " + 0);
  try {
   while (ch == 1) {
    System.out.println("Enter sender:");
    int s = Integer.parseInt(dis.readLine());
    System.out.println("Enter receiver:");
    int r = Integer.parseInt(dis.readLine());
    System.out.println("Enter Data:");
    String d = dis.readLine();
    System.out.print("Token passing:");
    for (int i = token; i != s; i++)
     System.out.print(" " + i + "->");
    System.out.println(" " + s);
    System.out.println("Sender " + s + "sending data: " + d);
    for (int i = s + 1; i != r; i = (i + 1) % n)
     System.out.println("data  " + d + " forwarded by " + i);
    System.out.println("Receiver " + r + "received data: " + d);
    token = s;

   }
  } catch (Exception e) {
  }
 }
}


[ Read More ]
Read more...
Tuesday, October 16, 2012

Function to Check IpAddress is within a Specified Range

Posted by Raju Gupta at 3:00 PM – 0 comments
 
The code snippet is used to check the IpAddress given is within a specified range. It will set the inRange boolean to true if IpAddress is within that range.

/**
  * @param args
  * @throws UnknownHostException 
  */
 public static void main(String[] args){
  // TODO Auto-generated method stub
  
  //Pass the IpAdress to check whether it is in the Specified Range
  String ipAddress = "";
  //IpAddress Ranges are to be Specified here.
  String ipAddressRange = "";
  boolean inRange = false;
  if (!ipAddressRange.isEmpty()){
   String[] addressRanges = ipAddressRange.split(",");
   for (String ipAddr:addressRanges){
    String[] ipAddrLowHigh = ipAddr.split("-");
    try {
     long ipAddrLower = ipToLong(InetAddress.getByName(ipAddrLowHigh[0]));         
     long ipAddrHigher = ipToLong(InetAddress.getByName(ipAddrLowHigh[1]));         
     long ipAddrToTest = ipToLong(InetAddress.getByName(ipAddress));  
     inRange = ipAddrToTest >= ipAddrLower && ipAddrToTest <= ipAddrHigher;
     System.out.println("True = If Ipaddress is within the range:::::"+inRange);
     if (inRange){
      break;
     }
    } catch (UnknownHostException ex){
     System.out.println("UnknownHostException Occurred in IFAUtils.isIpAddressRange:::"+ex.getMessage());
     ex.printStackTrace();
    }
   } 
  } 
 } 
 
 /**
  * Method ipToLong. converting ipAddress to Long value for given ipAddress is in available range.
  * @param ipAddress contains the System ipAddress. 
  * @return long return converted long value will return.
  */
 public static long ipToLong(InetAddress ipAddress) {         
  byte[] octets = ipAddress.getAddress();         
  long result = 0;         
  for (byte octet : octets) {             
   result <<= 8;             
   result |= octet & 0xff;         
  }         
  return result;     
 }  



[ Read More ]
Read more...
Friday, October 12, 2012

Network scanner java code

Posted by Raju Gupta at 10:51 PM – 0 comments
 
This code will list the devices connected to the network(hub) including wired/wireless

import java.io.IOException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class NetworkScan implements Runnable
{

 static Map devices=null;
 String flag;
 // search for local IP that is not 127.0.0.1 (other methods are not reliable)
  public String[] getLocalAddress() 
  {
   Enumeration<NetworkInterface> nets;
   try { nets = NetworkInterface.getNetworkInterfaces();
   } catch (SocketException e) {return null;}
         for (NetworkInterface netint : Collections.list(nets)) {
             Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
             for (InetAddress inetAddress : Collections.list(inetAddresses)) {
                 if (!inetAddress.isLoopbackAddress() 
                   && inetAddress.getHostAddress().matches("(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)")) 
                 {
                  //System.out.println("IP Address:"+inetAddress.getHostAddress());
                  return inetAddress.getHostAddress().split("\.");
                 }
             }
         }
         return null;
  }
  public String Update()
  {
   //System.out.println("nnnnnn ############################################ update########################################################################");
   String devicesData="";
   if(devices!=null&&!devices.isEmpty())
   {
   Set s = devices.entrySet();                
   Iterator i = s.iterator();
   
   while (i.hasNext()) 
   {                        //System.out.println("Devices"+i.next());
    
    //System.out.println(i.next());
    String[] tmp=i.next().toString().split("=");
    
    devicesData+=","+tmp[0]+":"+tmp[1];
    /*try {
     if (InetAddress.getByName(tmp[0]).isReachable(1000)) 
     {
      devicesData+=tmp[0]+":"+tmp[1]+":Active,";
     }
     else
     {
      devicesData+=tmp[0]+":"+tmp[1]+":InActive,";
     }
    } catch (UnknownHostException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
    */
    
    
   }
   }
   //System.out.println("################################################################################################################"+devicesData);
   return devicesData;
  }
  public void run()
  {
   //System.out.println("Running..."+flag);
   if(devices==null)
   {
    devices=new HashMap();
    //System.out.println("Map Created...");
   }
   String startIP, stopIP;
   String[] local = getLocalAddress();
   
   collectDeviceDetailsThreaad(local, "1", "7");
   
   System.out.println(flag+" milli sec-->"+System.currentTimeMillis());
   switch (Integer.parseInt(flag))
   {
   
   case 1:
    collectDeviceDetailsThreaad(local, "1", "7");
    break;
   case 2:
    collectDeviceDetailsThreaad(local, "8", "15");
    break;
   case 3:
    collectDeviceDetailsThreaad(local, "16", "22");
    break;
   case 4:
    collectDeviceDetailsThreaad(local, "23", "29");
    break;
   case 5:
    collectDeviceDetailsThreaad(local, "30", "36");
    break;
   case 6:
    collectDeviceDetailsThreaad(local, "37", "43");
    break;
   case 7:
    collectDeviceDetailsThreaad(local, "44", "50");
    break;
   case 8:
    collectDeviceDetailsThreaad(local, "51", "57");
    break;
   case 9: 
    collectDeviceDetailsThreaad(local, "58", "64");
    break;
   case 10:
    collectDeviceDetailsThreaad(local, "65", "71");
    break;
   case 11: 
    collectDeviceDetailsThreaad(local, "72", "78");
    break;
   case 12:
    collectDeviceDetailsThreaad(local, "79", "85");
    break;
   case 13: 
    collectDeviceDetailsThreaad(local, "86", "92");
    break;
   case 14:
   collectDeviceDetailsThreaad(local, "93", "99");
   break;
   case 15:
    collectDeviceDetailsThreaad(local, "100", "106");
    break;
   case 16:
    collectDeviceDetailsThreaad(local, "107", "113");
    break;
   case 17:
    collectDeviceDetailsThreaad(local, "114", "120");
    break;
   case 18:
    collectDeviceDetailsThreaad(local, "121", "127");
    break;
   case 19 :
    collectDeviceDetailsThreaad(local, "128", "134");
    break;
   case 20:
    collectDeviceDetailsThreaad(local, "135", "141");
    break;
   case 21:
    collectDeviceDetailsThreaad(local, "142", "148");
    break;
   case 22:
    collectDeviceDetailsThreaad(local, "149", "155");
    break;
   case 23:
    collectDeviceDetailsThreaad(local, "156", "162");
    break;
   case 24:
    collectDeviceDetailsThreaad(local, "163", "169");
    break;
   case 25:
    collectDeviceDetailsThreaad(local, "170", "176");
    break;
   case 26:
    collectDeviceDetailsThreaad(local, "177", "183");
    break;
   case 27:
    collectDeviceDetailsThreaad(local, "184", "190");
    break;
   case 28:
    collectDeviceDetailsThreaad(local, "191", "197");
    break;
   case 29:
    collectDeviceDetailsThreaad(local, "198", "204");
    break;
   case 30:
    collectDeviceDetailsThreaad(local, "205", "211");
    break;
   case 31:
    collectDeviceDetailsThreaad(local, "212", "218");
    break;
   case 32:
    collectDeviceDetailsThreaad(local, "219", "225");
    break;
   case 33:
    collectDeviceDetailsThreaad(local, "226", "232");
    break;
   case 34:
    collectDeviceDetailsThreaad(local, "233", "239");
    break;
   case 35:
    collectDeviceDetailsThreaad(local, "240", "247");
    break;
   case 36:
    collectDeviceDetailsThreaad(local, "248", "255");
    break;
    
    
    
   }
   
   
    
   
  }
  
  
  public void collectDeviceDetailsThreaad(String[] local,String startingIP,String endingIP)
  {
   
   String startIP, stopIP;
   

   //startIP="192.168.1.1";
   startIP = local[0]+"."+local[1]+"."+local[2]+"."+startingIP;
   stopIP = local[0]+"."+local[1]+"."+local[2]+"."+endingIP;
   String[] from = startIP.split("\.");
   String[] to = stopIP.split("\.");
   int[] start = new int[4], stop = new int[4];
   for (int i = 0; i < 4; i++) 
   {
    start[i] = Integer.parseInt(from[i]);
    stop[i] = Integer.parseInt(to[i]);
   }
   for (int a = start[0]; a <= stop[0]; a++) {
    for (int b = start[1]; b <= stop[1]; b++) {
     for (int c = start[2]; c <= stop[2]; c++) {
      for (int d = start[3]; d <= stop[3]; d++) {
       //if (!run) return;
       try {
      
        
        if (InetAddress.getByName(a+"."+b+"."+c+"."+d).isReachable(2000)) 
        {
         

         devices.put(a+"."+b+"."+c+"."+d, InetAddress.getByName(a+"."+b+"."+c+"."+d).getHostName()+":Active");
        
         
        }
        else
        {
         if(devices.containsKey(a+"."+b+"."+c+"."+d))
         {
          
          devices.put(a+"."+b+"."+c+"."+d, InetAddress.getByName(a+"."+b+"."+c+"."+d).getHostName()+":InActive");
          
         }
        }
       } catch (IOException e) {System.out.println("exception..");}
       //progress.setValue(++pNow);
      }
     }
    }
   }
   
   
   
   
  }
  
  
}

[ Read More ]
Read more...
Tuesday, October 9, 2012

TRACE ROUTE COMMAND TO KNOW THE EXACT SERVER NAME WHERE THE PACKET GOT FAILED

Posted by Raju Gupta at 1:02 PM – 0 comments
 
It will track the details of each packet being moved from one hop to the other, in the way from Source to Destination.

public static void findTraceRoute(String errorNumber, String hostname)
 {
    String strCmd ="traceroute"+" "+hostname;
   String strHostName= hostname;
   String strResult="";
   String strError="";
   String s = null;
   Process p=null;
   BufferedReader stdInput=null;
   BufferedReader stdError=null;
   
   try {

     // run the Unix command specified in the "strCmd"
  
     p = Runtime.getRuntime().exec(strCmd);
     
     stdInput = new BufferedReader(new
      InputStreamReader(p.getInputStream()));
     
     // read the output from the command
           
      while ((s = stdInput.readLine()) != null) {
        strResult=strResult+s;//Append the output to the strresult String
     }//end of while loop
 //Log the output(strResult) of the TRACE ROUTE Command into the Message.log File
               
   }
    catch (IOException e) {
   
 // read any errors from the attempted command and store it in the strError String
     try
     {
      stdError = new BufferedReader(new
      InputStreamReader(p.getErrorStream()));
       
      while ((s = stdError.readLine()) != null) {
       strError=strError+s;
       }
     }catch(IOException ex){
      
     }
    }finally {
     //Close the Stream Readers
     try
     {
      stdInput.close();
      stdError.close();
    
     } catch(Exception e){
           }
      //Termination of the Process
      p.destroy();
    }//end of finally block
}//end of trace route method

[ Read More ]
Read more...
Older Posts
Subscribe to: Posts ( Atom )
  • Popular
  • Recent
  • Archives
Powered by Blogger.
 
 
 
© 2011 Java Programs and Examples with Output | Designs by Web2feel & Fab Themes

Bloggerized by DheTemplate.com - Main Blogger