Source of LocalIPAddress.java


  1: //LocalIPAddress.java
  2: //Finds the IP address of your local machine.

  4: import java.awt.Color;
  5: import java.awt.FlowLayout;
  6: import java.awt.event.ActionEvent;
  7: import java.awt.event.ActionListener;
  8: import java.net.InetAddress;
  9: import java.net.UnknownHostException;
 10: import javax.swing.JFrame;
 11: import javax.swing.JButton;
 12: import javax.swing.JTextField;
 13: import javax.swing.SwingConstants;


 16: public class LocalIPAddress extends JFrame
 17: implements ActionListener
 18: {
 19:     private JButton displayButton;
 20:     private JTextField textOfIPAddress;

 22:     public static void main(String [] args)
 23:     {
 24:         LocalIPAddress app = new LocalIPAddress("Finding Local IP Address");
 25:         app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 26:         app.setSize(440, 80);
 27:         app.setVisible(true);
 28:     }

 30:     LocalIPAddress(String s)
 31:     {
 32:         super(s);
 33:         setLayout(new FlowLayout());

 35:         displayButton = new JButton("Click here to display the IP " +
 36:                                     "address of your local machine ...");
 37:         textOfIPAddress = new JTextField(37);
 38:         displayButton.addActionListener(this);
 39:         textOfIPAddress.addActionListener(this);
 40:         add(displayButton);
 41:         add(textOfIPAddress);
 42:         getContentPane().setBackground(Color.CYAN);
 43:     }

 45:     public void actionPerformed(ActionEvent event)
 46:     {
 47:         try
 48:         {
 49:             InetAddress address = InetAddress.getLocalHost();
 50:             textOfIPAddress.setText(address.toString().replace('/', ':'));
 51:             textOfIPAddress.setHorizontalAlignment(JTextField.CENTER);
 52:         }
 53:         catch (UnknownHostException e)
 54:         {
 55:             textOfIPAddress.setText("Could not find the local address");
 56:         }
 57:     }
 58: }