YouTip LogoYouTip

Net Localip

# Java Example - Get Local IP Address and Hostname [![Image 3: Java Example](#) Java Example](#) In Java, you can use the standard networking library to get the local IP address and hostname. The following example demonstrates how to use the `getLocalHost` and `getLocalAddress()` methods of the `InetAddress` class to get the local hostname and IP address: ## Main.java File import java.net.InetAddress; import java.net.UnknownHostException; public class NetworkInfo{public static void main(String[]args){try{// Get local host object InetAddress localHost = InetAddress.getLocalHost(); // Get hostname String hostName = localHost.getHostName(); System.out.println("Hostname: " + hostName); // Get IP address String hostAddress = localHost.getHostAddress(); System.out.println("IPAddress.: " + hostAddress); }catch(UnknownHostException e){System.err.println("Unable to get local IP address.andHostname: " + e.getMessage()); e.printStackTrace(); }}} ### Explanation * `InetAddress.getLocalHost()`: Gets the `InetAddress` object representing the local host. * `getHostName()`: Gets the hostname of the local host. * `getHostAddress()`: Gets the IP address of the local host. ### Exception Handling * `UnknownHostException`: Thrown when the local hostname or IP address cannot be determined. The output of the above code is: Hostname: your-hostname IPAddress.: 192.168.1.2 [![Image 4: Java Example](#) Java Example](#)
← Data AddException Printstack β†’