In today’s post we are going to learn how to get the ip address.This is very simple and easy program among all basic programs of java.In this program we are importing the classes “import java.net.InetAddress”,”import java.net.UnknownHostException”.Here we are declaring a variable for InetAddress class. This variable is used to store the ip address. If any Error is occurred then we need to handle those errors.For this we are including the try block and catch block to handle these errors.
Let us write the code for this:
import java.net.InetAddress; import java.net.UnknownHostException; public class ip_address { public static void main(String[] args) { InetAddress ip; try { ip = InetAddress.getLocalHost(); System.out.println("Current IP address : " + ip.getHostAddress()); } catch(UnknownHostException e) { System.out.println(e); } } }
Output:
You can download the source code:download