How to find your IP address and computer/host name
The InetAddress class can be used to perform Domain Name Server (DNS) lookups. The host name can either be a machine name, such as "mail.yahoo.com", or a textual representation of its IP address . The java.net.InetAddress class provides methods to get the IP of any host name for example www.yahoo.com, www.facebook.com etc.InetAddress has no public constructor, so you must obtain instances via a set of static methods.
InetAddress ip = InetAddress.getLocalHost();
Java InetAddress Class is used to encapsulate the two thing.
- Numeric IP Address
- The domain name for that address
InetAddress ip = InetAddress.getLocalHost();
2. getByName(): getByName method returns an InetAddress for a host name passed to it as a parameter argument. If this method unable to find out the host name, it throw an UnknownHostException .
InetAddress address = InetAddress.getByName("localhost");
Example
import java.net.InetAddress;
import java.net.UnknownHostException;
public class TestClass {
public static void main(String[] args) {
try{
InetAddress ip = InetAddress.getLocalHost();
String hostname = ip.getHostName();
System.out.println("IP address : " + ip);
System.out.println("Computer Name : " + hostname);
InetAddress address = InetAddress.getByName("localhost");
System.out.println(address.toString());
}catch(Exception ex){
System.out.println(ex);
}
}
}
Related Topics