import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class GetLocalIpAddress {
public static void main(String[] args) {
Map<String, List<String>> map = getLocalIP();
for(String key : map.keySet()) {
System.out.println(key + ": " + map.get(key).toString());
}
}
public static Map<String, List<String>> getLocalIP() {
Map<String, List<String>> map = new HashMap<String, List<String>>();
Enumeration<NetworkInterface> e1;
try {
e1 = NetworkInterface.getNetworkInterfaces();
while (e1.hasMoreElements()) {
NetworkInterface ni = e1.nextElement();
List<String> ips = new LinkedList<String>();
map.put(ni.getName(), ips);
Enumeration<InetAddress> e2 = ni.getInetAddresses();
while (e2.hasMoreElements()) {
InetAddress ia = e2.nextElement();
if(ia instanceof Inet6Address) {
continue; // omit IPv6 address
}
ips.add(ia.getHostAddress());
}
}
} catch (SocketException e) {
e.printStackTrace();
}
return map;
}
}
output:
lo: [127.0.0.1]
eth0: [192.168.2.68, 192.168.2.67]