The shortest way:
try { InetAddress thisIp =InetAddress.getLocalHost(); System.out.println("IP:"+thisIp.getHostAddress()); } catch(Exception e) { e.printStackTrace(); }
However, getLocalHost docs say:
If there is a security manager, its checkConnect method is called with the local host name and -1 as arguments to see allowed. If the operation is not permitted, an InetAddress representing the return address is returned.
and in some cases, InetAddress.getLocalHost() does not access your interfaces, it just returns the constant 127.0.0.1 (for IPv4))
I think NetworkInterface.getNetworkInterfaces is what you need to list all the features. Here is an example that does not show virtual addresses, but works for the "main" interfaces:
import java.net.*; import java.util.*; public class Test { public static void main(String[] args) throws Exception
As an alternative:
Try using this (the first output should be IP after the PC name):
InetAddress[] localaddr; String computername = null; try { computername = InetAddress.getLocalHost().getHostName();//get pc name } catch (UnknownHostException ex) { ex.printStackTrace(); } System.out.println(computername); try { localaddr = InetAddress.getAllByName(computername); for (int i = 0; i < localaddr.length; i++) { System.out.println("\n" + localaddr[i].getHostAddress()); } } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); }
References
source share