Reputation: 147
Is there an in-built programmatic way to find out if the machine is multi-homed or not? I have the snippet below which can do the task but looks cumbersome. Is there a better way to do this?
int count = 0;
try {
InetAddress localhost = InetAddress.getLocalHost();
InetAddress[] allMyIps = InetAddress.getAllByName(localhost.getCanonicalHostName());
if (allMyIps != null && allMyIps.length > 1) {
for (int i = 0; i < allMyIps.length; i++) {
if (allMyIps[i].isLoopbackAddress() == false) count++;
}
}
if (count > 1) System.out.println("Multihomed");
} catch (UnknownHostException e) {
e.printStackTrace();
}
I am skeptical about this since all hybrid NIC have a IpV6 and an IPv4 configured on it (at least in windows 7) by default. Hence these come out as an multi homed. Is there an effective way to do this?
Upvotes: 0
Views: 247
Reputation: 11
You could use the "NetworkInterface" class in java. If there are more than one interfaces other than loopback interface, its multi-homed.
Enumeration<NetworkInterface> ifs = NetworkInterface.getNetworkInterfaces();
int count = 0;
while (ifs.hasMoreElements()) {
if (count > 1) {
break;
}
if(!ifs.nextElement().isLoopback()) {
count++;
}
}
System.out.println(count > 1 ? "Multi-homed" : "Not Multi-homed");
Upvotes: 1