Print My IP Address – Java Code

Objective: Write a java program to print your IP address.

Approach:

  • Get the local host address of your system using getLocalHost() method.
  • Use getHostAddress() method to get the IP address from local host address.

Code:

import java.net.InetAddress;
import java.net.UnknownHostException;
public class PrintIPAddress {
public static void getIPAddress(){
try {
//get the local host
InetAddress localHost = InetAddress.getLocalHost();
//get the ipaddress
String ipaddress = localHost.getHostAddress();
System.out.println("IP ADDRESS is : " + ipaddress);
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
getIPAddress();
}
}

view raw
PrintIPAddress.java
hosted with ❤ by GitHub


Output:

IP ADDRESS is : 192.162.1.9