To get IP address of the current computer that’s running the Java application, uses InetAddress.getLocalHost()
to initialize the InetAddress
object and InetAddress.getHostAddress() to get the current IP address.
Full example.
package br.com.ziben; import java.net.InetAddress; import java.net.UnknownHostException; public class app{ public static void main(String[] args){ InetAddress ip; try { ip = InetAddress.getLocalHost(); System.out.println("Current IP address : " + ip.getHostAddress()); } catch (UnknownHostException e) { e.printStackTrace(); } } }
Output
Current IP address : 192.168.0.185
IP 192.168.0.185 is my computer’s IP address to run this example, let compare with Ubuntu’s ifconfig
ifconfig output…
eth0 Link encap:Ethernet Endereço de HW b8:ac:6f:74:b7:51 inet end.: 192.168.0.185 Bcast:192.168.0.255 Masc:255.255.255.0 endereço inet6: fe80::baac:6fff:fe74:b751/64 Escopo:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Métrica:1 pacotes RX:19403 erros:0 descartados:0 excesso:0 quadro:0 Pacotes TX:14705 erros:0 descartados:0 excesso:0 portadora:0 colisões:0 txqueuelen:1000 RX bytes:10498710 (10.4 MB) TX bytes:2187781 (2.1 MB) IRQ:45 Endereço de E/S:0x2000
Same, InetAddress.getHostAddress()
is working as expected.