Ниже будут отображаться все доступные адреса IPv4 без обратной связи на хосте.Вы также можете легко адаптировать его для получения адресов IPv6.
public static void main(String...args) {
List<InetAddress> addresses = getNonLocalIPV4Addresses();
for (InetAddress addr: addresses) {
System.out.println("address: " + addr.getHostAddress());
}
}
/**
* Get a list of all known non-local IP v4 addresses for the current host.
* @return a List of <code>InetAddress</code>, may be empty but never null.
*/
public static List<InetAddress> getNonLocalIPV4Addresses() {
return getIPAddresses(new InetAddressFilter() {
public boolean accepts(InetAddress addr) {
return (addr instanceof Inet4Address)
&& !(addr.isLoopbackAddress()) || "localhost".equals(addr.getHostName()));
}
});
}
/**
* Get a list of all known IP addresses for the current host,
* according to the specified filter.
* @param filter filters out unwanted addresses.
* @return a List of <code>InetAddress</code>, may be empty but never null.
*/
public static List<InetAddress> getIPAddresses(InetAddressFilter filter) {
List<InetAddress> list = new ArrayList<InetAddress>();
try {
Enumeration<NetworkInterface> interfaces =
NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface ni = interfaces.nextElement();
Enumeration<InetAddress> addresses = ni.getInetAddresses();
while (addresses.hasMoreElements()) {
InetAddress addr = addresses.nextElement();
if ((filter == null) || filter.accepts(addr)) list.add(addr);
}
}
} catch(Exception e) {
e.printStackTrace();
}
return list;
}
/**
* Filter interface for the methods discovering available IP addresses.
*/
public interface InetAddressFilter {
/**
* Determine whether the specified address is accepted.
* @param addr the address to check.
* @return true if the address is accepted, false otherwise.
*/
boolean accepts(InetAddress addr);
}