Programming Blog

This blog is about technical and programming questions and there solutions. I also cover programs that were asked in various interviews, it will help you to crack the coding round of various interviews

Sunday 19 August 2018

Java program to get the IP address of localhost

Below example shows how to get IP address of a host or machine. You can get it by using InetAddress class. getLocalHost() method returns the information about the host, and returns InetAddress object. If you call getHostAddress() method, you can get IP address of the host.



import java.net.InetAddress;
import java.net.UnknownHostException;
public class MyIpAddress 
{
public static void main(String a[])
{    
try 
{            
InetAddress ipAddr = InetAddress.getLocalHost();            
System.out.println(ipAddr.getHostAddress());        

catch (UnknownHostException ex) 
{            
ex.printStackTrace();        
}    
}
}

No comments:

Post a Comment