Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
Here’s a guide with multiple examples in JAVA to get hostname or IP address from URL or localhost using JAVA API.
We get a dedicated JAVA class to help with it java.net.InetAddress
Use method java.net.InetAddress.getLocalHost()
. It returns the localhost address. It retrieves the name of the system host and resolves it into an InetAddress.
Use method java.net.InetAddress.getHostAddress()
. It returns the IP address of the host. In case of localhost, it returns 127.0.0.1
Use method java.net.InetAddress.getHostName()
. It gives the URL/hostname of the above-retreived IP address.
package com.mytrashcode; import java.net.InetAddress; class HostNameExample { public static void main(String args[]) throws Exception { try { InetAddress inetAddress = InetAddress.getLocalHost(); System.out.println("IP Address:- " + inetAddress.getHostAddress()); System.out.println("Host Name:- " + inetAddress.getHostName()); System.out.println("Localhost:- " + inetAddress.getLocalHost()); } catch (UnknownHostException e) { e.printStackTrace(); } } }
[su_label type=”info”]Also read: [/su_label] : Advantages of Golang over Java and Python
Result :
IP Address:- 169.254.124.231 Host Name:- mytrashcode Localhost:- localhost
inetAddress.getHostName());
is bound to fail in some circumstances:
Comment and let us know if this java get hostname guide helped you or in case you would love to see some other guide on our blog.