Write a Java program to print the machine IP address
Introduction
Write a simple Java program to output machine IP address and hostname to the console. InetAddress class is used. import java.net.InetAddress and wrap the code in a try-catch block.
The InetAddress java class provides methods to resolve hostnames to
their IP addresses and vice versa. Below is a sample Java program to print
hostname and IP Address.
Java Program
import java.net.InetAddress; import java.net.UnknownHostException; /******************************************** // IPAddressDemo.java // // www.TestingDocs.com ********************************************/ public class IPAddressDemo { public static void main(String[] args) { //try-catch block try { InetAddress hostMachine = InetAddress.getByName("localhost"); System.out.println(hostMachine.getHostName()); //Print hostname System.out.println(hostMachine.getHostAddress());//Print ipaddress }catch(UnknownHostException uhe) { uhe.printStackTrace(); } } }