Learn how to get host name and IP address of local system in Java using the InetAddress class. The InetAddress class belongs to the java.net package and provides methods for working with IP addresses and host names. An IP address can be represented as either a 32-bit IPv4 address or a 128-bit IPv6 address.
Code Explanation (Step-by-Step)
- Use InetAddress.getLocalHost() to retrieve information about the local machine and store the in the inetAdd variable .
- Call inetAdd.getHostName() to obtain the system host name.
- Call inetAdd.getHostAddress() to obtain the IP address in readable format.
- Now print the host name and IP address of the local system.
import java.net.InetAddress;
import java.net.UnknownHostException;
public class MyHostAddress {
public static void main(String[] args) throws UnknownHostException {
InetAddress inetAdd = InetAddress.getLocalHost();
System.out.println("Host Name : " + inetAdd.getHostName());
System.out.println("IP Address : " + inetAdd.getHostAddress());
System.out.println("Local Host : " + inetAdd);
}
}
Output :-
Host Name : hello-PC
IP Address : 100.100.0.100
Local Host : hello-PC/100.100.0.100
Exception Handling Using UnknownHostException
UnknownHostException is a checked exception that occurs when the IP address of a host cannot be determined or the host name cannot be resolved. It is commonly handled when working with the InetAddress class.
try {
InetAddress inetAddress = InetAddress.getLocalHost();
System.out.println(inetAddress.getHostAddress());
} catch (UnknownHostException e) {
System.out.println("Unable to find the host address.");
}