import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
public class GetIP{
public static void main(String[] args) {
try
{
InetAddress addr1 = InetAddress.getLoopbackAddress();
InetAddress addr2 = InetAddress.getLocalHost();
System.out.println("Host name:"+addr1.getHostName());
System.out.println("IP:"+addr1.getHostAddress());
System.out.println("Host name:"+addr2.getHostName());
System.out.println("IP:"+addr2.getHostAddress());
}catch(UnknownHostException e) {e.printStackTrace(); }
}
}
The two methods above are able to get the IP addresses and host names of the local machine only. If you want to get the IP addresses of a remote machine (e.g. IP addresses of a web server), you will use the getByName method. This method accepts the host name of the remote machine. You will use the URL class to point to the remote host.
public static void getIPfromURL(String strurl){
try {
URL url=new URL(strurl);
InetAddress address = InetAddress.getByName(url.getHost());
System.out.println(address.getHostAddress());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
