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.
Hi
How do I get port number?
Hi Kamil – what do you mean?
Thank you for this tutorial
I’m in big trouble finding a Good solution to my problem (I need this as a project), and I hope you can help me.
I need some help on a small program in C or C++ (or java) that can give me @IP and @MAC and HOSTNAME of another computer [not my computer] in a local network [between 2 computers], and to save this result in an external file (txt file or excel or html page …) I am a beginner on programming, I don’t know how to start and from what I have to start. All I know is that this program can be done using sockets. (Sorry for my bad english !)
Thanks in advance for your HELP.