Java Program to print the IP address of your computer.
Objective
Write a Java program to find and print the IP address and Hostname of the local computer.
Algorithm / Approach
- Import
java.net.*. - Call the static method
InetAddress.getLocalHost(). - Extract the IP using
inet.getHostAddress(). - Extract the PC name using
inet.getHostName(). - Print the results.
GetIP.java
import java.net.*;
class GetIP
{
public static void main(String args[])
throws UnknownHostException {
InetAddress inet;
inet = InetAddress.getLocalHost();
System.out.println("Address : "+inet);
String ip = inet.getHostAddress();
System.out.println("IP Address: "+ip);
String hn = inet.getHostName();
System.out.println("Host Name : "+hn);
}
}
Expected Output
Address : FAIZ/192.168.43.12 IP Address : 192.168.43.12 Host Name : FAIZ
Explanation of the Program
- The
java.netpackage contains all classes related to networking. - The
InetAddressclass is used to encapsulate both the numerical IP address and the domain name for that address. This is highly useful in client-server applications to log which specific machine on the network is making a request.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)