Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to print the IP address of your computer.

Java Code Example — Utility Programs

ADVERTISEMENT

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

  1. Import java.net.*.
  2. Call the static method InetAddress.getLocalHost().
  3. Extract the IP using inet.getHostAddress().
  4. Extract the PC name using inet.getHostName().
  5. 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.net package contains all classes related to networking.
  • The InetAddress class 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)
ADVERTISEMENT