Here, we are going to explore a method to retrieve the IPAddress of the local system in a very simple example. For this, we use getByName() method of InetAddress class to create a object that contains IP address for the given host name.
ReadIPAddress
Here, we are going to explore a method to retrieve the IPAddress of the local system in a very simple example. For this, we use getByName() method of InetAddress class to create a object that contains IP address for the given host name. Using this object we can get IP address using method getHostAddress(). Now we can use the print statement to print this value. If the user enters the host name by keyboard then IP address of local machine will be displayed on console.
getHostAddress(): This method of InetAddress class returns an IPAddress of local system.
Here is the code of this program:
import java.net.*; import java.io.*; public class ReadIPAddress{ public static void main(String[] args )throws IOException { BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter the host name: "); String hostname = input.readLine(); try { InetAddress inetadd = InetAddress.getByName(hostname); System.out.println("IP address is: " + inetadd.getHostAddress()); } catch(UnknownHostException e ){ System.out.println("Could not find IP address for: " + hostname); } } }
Here is the Output of this program:
C:\rose>java ReadIPAddress Enter the host name: roseindi IP address is: 192.168.10.104 C:\rose> |