In Java, you can use InetAddress.getLocalHost()
to get the Ip Address of the current Server running the Java app and InetAddress.getHostName()
to get Hostname of the current Server name.
package com.crunchify.tutorials; import java.net.InetAddress; import java.net.UnknownHostException; /** * @author Crunchify.com */ public class CrunchifyGetIPHostname { public static void main(String[] args) { InetAddress ip; String hostname; try { ip = InetAddress.getLocalHost(); hostname = ip.getHostName(); System.out.println("Your current IP address : " + ip); System.out.println("Your current Hostname : " + hostname); } catch (UnknownHostException e) { e.printStackTrace(); } } }
Output:
Your current IP address : appshah-mac/192.168.0.1 Your current Hostname : appshah-mac
Another must read:
On the face of it, InetAddress.getLocalHost()
should give you the IP address of this host. The problem is that a host could have lots of network interfaces, and an interface could be bound to more than one IP address. And to top that, not all IP addresses will be reachable from off the machine. Some could be virtual devices, and others could be private network IP addresses.
What this means is that the IP address returned by InetAddress.getLocalHost()
might not be the right one to use.
How can you deal with this?
- One approach is to use Java’s
NetworkInterface.getNetworkInterfaces()
API to get all of the known network interfaces on the host, and then iterate over each NI’s addresses. - Another approach is to (somehow) get the externally advertised FQDN for the host, and use
InetAddress.getByName()
to look up the primary IP address. (But how do you get it, and how do you deal with a DNS-based load balancer?) - A variation of the previous is to get the preferred FQDN from a config file or a command line parameter.
- Another variation is to to get the IP address from a config file or a command line parameter.
In summary, InetAddress.getLocalHost()
will typically work, but you may need to provide an alternative method for the cases where your code is run in an environment with “complicated” networking.