I need to get computer IP from Ubuntu using Java. I tried with InetAddress.getLocalHost.getHostAddress().toString();
but it returns 127.0.0.1
. I was searching for solution and found out this code:
NetworkInterface ni = NetworkInterface.getByName("eth0");
Enumeration<InetAddress> inetAddresses = ni.getInetAddresses();
while(inetAddresses.hasMoreElements()) {
InetAddress ia = inetAddresses.nextElement();
if(!ia.isLinkLocalAddress()) {
System.out.println("IP: " + ia.getHostAddress());
}
}
}
This code worked for me but problem is when computer uses "eth1" interface or computer can use wireless adapter to connect to network (wlan0). On that situatuon program will fail. Can you guys advise me with safe method to get IP from UNIX systems ? Regards.