package be.iminds.ilabt.jfed.connectivity_tester;

import java.net.*;
import java.util.Enumeration;
import java.util.List;

/**
 * User: twalcari
 * Date: 12/19/13
 * Time: 4:26 PM
 */
public class HasIPv4AddressTest implements ConnectivityTest {

    public HasIPv4AddressTest() {
    }

    @Override
    public String getName() {
        return "Check for IPv4-address";
    }

    @Override
    public boolean isLoginRequired() {
        return false;
    }

    @Override
    public ConnectivityTestResult call() {
        try {
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            while (interfaces.hasMoreElements()) {
                NetworkInterface interf = interfaces.nextElement();
                if (interf.isUp() && !interf.isLoopback()) {
                    List<InterfaceAddress> adrs = interf.getInterfaceAddresses();
                    for (InterfaceAddress adr : adrs) {
                        InetAddress inadr = adr.getAddress();
                        if (inadr instanceof Inet4Address) {
                            return new ConnectivityTestResult(Status.SUCCEEDED,
                                    "Found network-address " + inadr.getHostAddress() + " on interface " + interf.getDisplayName());
                        }
                    }
                }
            }
        } catch (SocketException e) {
            return new ConnectivityTestResult(Status.FAILED, e);
        }
        return new ConnectivityTestResult(Status.FAILED,
                "Could not find non-loopback IPv4-address for this computer");
    }
}
