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 HasIPv6AddressTest implements ConnectivityTest {

    @Override
    public String getName() {
        return "Check for IPv6-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 Inet6Address && !inadr.isLinkLocalAddress()) {
                            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 a public IPv6-address for this computer");

    }
}
