EN
Java - get host name and IP address of local machine
6 points
In this short article, we would like to show how to get localhost host name and IP address using Java.
Quick solution:
xxxxxxxxxx
1
// import java.net.InetAddress;
2
3
InetAddress address = InetAddress.getLocalHost();
4
5
String hostName = address.getHostName();
6
String hostAddress = address.getHostAddress(); // IPv4 or IPv6
xxxxxxxxxx
1
import java.net.InetAddress;
2
3
public class Program {
4
5
public static void main(String[] args) throws Exception {
6
7
InetAddress address = InetAddress.getLocalHost();
8
9
System.out.println("My host name is: " + address.getHostName());
10
System.out.println("My IP address is: " + address.getHostAddress());
11
}
12
}
Example output:
xxxxxxxxxx
1
My host name is: DESKTOP-U147DNR
2
My IP address is: 192.168.56.1
xxxxxxxxxx
1
import java.net.InetAddress;
2
import java.net.NetworkInterface;
3
import java.util.Enumeration;
4
5
public class Program {
6
7
public static void main(String[] args) throws Exception {
8
9
printNetworkInterfaces(NetworkInterface.getNetworkInterfaces());
10
}
11
12
private static void printNetworkInterfaces(Enumeration<NetworkInterface> networkInterfaces) {
13
while (networkInterfaces.hasMoreElements()) {
14
NetworkInterface networkInterface = networkInterfaces.nextElement();
15
System.out.println("Interface name: " + networkInterface.getName());
16
printInetAddresses(networkInterface.getInetAddresses());
17
}
18
}
19
20
private static void printInetAddresses(Enumeration<InetAddress> inetAddresses) {
21
while (inetAddresses.hasMoreElements()) {
22
InetAddress inetAddress = inetAddresses.nextElement();
23
System.out.println(" " + inetAddress.getHostName() + " " + inetAddress.getHostAddress());
24
}
25
}
26
}
Example output:
xxxxxxxxxx
1
Interface name: lo
2
127.0.0.1 127.0.0.1
3
0:0:0:0:0:0:0:1 0:0:0:0:0:0:0:1
4
Interface name: eth0
5
DESKTOP-U147DNR 192.168.56.1
6
DESKTOP-U147DNR fe80:0:0:0:8c21:8c20:8ae8:fd66%eth0
7
Interface name: wlan0
8
DESKTOP-U147DNR.home 192.168.1.113
9
80fe:0:0:0:5522:2db2:7ea1:4c44%wlan0 80fe:0:0:0:5522:2db2:7ea1:4c44%wlan0