Java

TOPIC 20 – INTRO TO NETWORKING

 

 

LESSON NOTE

 

 

INTRO

 

Computers on a network are similar to houses on a street.  They all have a unique address.  This address is called an IP address.  An IP address consists of four numbers ranging between 0 and 255.  An example is 10.211.8.112.  Note how the numbers are separated by a dot.  That is the standard notation for IP addresses.

 

Computers are also given a name called a host name.

 

USING THE DOS PROMPT

 

You can open the command prompt by searching for “command prompt” or “cmd”. (See below.)

 

 

To see your IP address, you can use the command ipconfig.

 

To see your host name, you can use the command hostname.

 

You can check the connection between yourself and another computer by using either ping ipaddress or ping hostname.  Of course, in both cases, we need to use the ip address or the host name of the other computer.

 

For example, lets say I plan to communicate with the computer at IP address 10.211.8.112.  I can check the connection between it and my computer by typing ping 10.211.8.112.

 

GETTING THIS INFO IN JAVA

 

We can also get the IP address and host name information.  Java provides a class that gets this information for us.  It is the InetAddress class.

 

To use this class, you need the following import statement:

 

import java.net.*;

 

You first create an InetAddress object.  Strangely, you do not use a constructor call for this.  A static method from inside the InetAddress class is used.

 

InetAddress me = InetAddress.getLocalHost();

 

Error Handling

 

Wait, there is a bit of bad news here.  The line above can cause an exception.  There could be complications in the creation of this object.  Therefore, you have two options. 

 

OPTION 1 - You can add the following words

 

throws UnknownHostException

 

at the end of the method prototype that contains this statement.

 

OPTION 2 – You can use a try/catch statement around the statement.

 

Using the InetAddress object me, you can now get your IP address and your host name.

 

String myIP = me.getHostAddress();

 

String host = me.getHostName();

 

FULL EXAMPLE USING ERROR HANDLING OPTION 1

 

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

   {

      InetAddress me = InetAddress.getLocalHost();

     

      String myIP = me.getHostAddress();

      String host = me.getHostName();

     

      System.out.println(myIP);

      System.out.println(host);

   }

 

FULL EXAMPLE USING ERROR HANDLING OPTION 2

 

   public static void main(String[] args)

   {     

      try

      {

         InetAddress me = InetAddress.getLocalHost();

        

         String myIP = me.getHostAddress();

         String host = me.getHostName();

     

         System.out.println(myIP);

         System.out.println(host);

      }

      catch(UnknownHostException e)

      {

         System.out.println("Could not get the local host.");

      }

   }