I have the following code which is supposed to get only the IPv4 addresses of all active interfaces, but it still returns an IPv6 address on some computers.
public static List<List> getIpAddress() {
List<String> ip = new ArrayList<>();
List<List> ipRefined = new ArrayList<>();
try {
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface iface = interfaces.nextElement();
if (iface.isLoopback() || !iface.isUp())
continue;
Enumeration<InetAddress> addresses = iface.getInetAddresses();
while(addresses.hasMoreElements()) {
ip.add(addresses.nextElement().getHostAddress());
}
}
} catch (SocketException e) {
throw new RuntimeException(e);
}
for(int x = 0; x < ip.size(); x++){
if(ip.get(x).contains("%")){
try {
if (ip.get(x + 1).contains(".")) {
List<String> tempList = new ArrayList<>();
tempList.add(ip.get(x).substring(ip.get(x).indexOf("%") + 1));
tempList.add(ip.get(x + 1));
ipRefined.add(tempList);
}
} catch (IndexOutOfBoundsException ae) {
}
}
}
return ipRefined;
}
I've tried to specify using only IPv4 by using System.setProperty("java.net.preferIPv4Stack" , "true");
, but this only causes getIpAddress()
to return an empty list. How should I be getting the IPv4 of active interfaces without the use of string manipulation?
EDIT:
Using System.setProperty("java.net.preferIPv4Stack" , "true");
always causes getIpAddress()
to return an empty list.
addresses
enumeration, what about checking if each addressinstanceof Inet4Address
? – Albaneseif (ip.get(x + 1).contains("."))
. I rewrote some of my code to useinstanceof
instead of usingcontains()
, but it won't change anything. I'm going to update the question with one more detail. – Padnag