How to get the ip of the computer on linux through Java ?
I searched the net for examples, I found something regarding NetworkInterface class, but I can't wrap my head around how I get the Ip address.
What happens if I have multiple network interfaces running in the same time ? Which Ip address will be returned.
I would really appreciate some code samples.
P.S: I've used until now the InetAddress class which is a bad solution for cross-platform applications. (win/Linux).
Do not forget about loopback addresses, which are not visible outside. Here is a function which extracts the first non-loopback IP(IPv4 or IPv6)
The simplest solution in my case was
Socket.getLocalAddress()
. I had to open the Socket specifically for that purpose, but with all the NetworkInterfaces on my Ubuntu 10.04 machine it was the only way to get the external IP address.This code worked 4me:
From Java Tutorial
Why is
InetAddress
not a good solution? I don't see anything in the docs about cross platform compatibility?This code will enumerate all network interfaces and retrieve their information.
The following is sample output from the example program:
It's not ok to just return the first non-loopback interface as it might have been created by some software like Parallels. It's a better bet to try fishing for the eth0.