package network;

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

import test.App;

public class Tools {
	
	public static InetAddress getLocalIp(){
		try{
			InetAddress address = InetAddress.getLocalHost();
			return address;
		}
		catch (UnknownHostException e){
			System.out.println ("Could not find local address!");
		}
		return null;
	}
	
	
	//Renvoie un tableau d'InetAdress 
	//le premier élement est l'adresse locale de la machine 
	//le deuxieme l'adresse de broadcast
	public static InetAddress[] getAdress() {
        Enumeration<NetworkInterface> interfaces = null;
        InetAddress localAdress = null;
        InetAddress broadcastAddress = null;
        InetAddress[] tab = {null,null};
        try {
            interfaces = NetworkInterface.getNetworkInterfaces();
            while (interfaces.hasMoreElements())
            {
                NetworkInterface networkInterface = interfaces.nextElement();
                if (networkInterface.getName().equals(App.interfaceRzo)){
                    localAdress = networkInterface.getInterfaceAddresses().get(0).getAddress();
                    tab[0] = localAdress;
                    broadcastAddress = networkInterface.getInterfaceAddresses().get(0).getBroadcast();
                    tab[1] = broadcastAddress;
                    System.out.println("Found adress : " + localAdress);
                    break;
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return tab;
    }
	
	public static void printInterfaces() {
        Enumeration<NetworkInterface> interfaces = null;
        try {
            interfaces = NetworkInterface.getNetworkInterfaces();
            while (interfaces.hasMoreElements())
            {
                NetworkInterface networkInterface = interfaces.nextElement();
                try {
                InetAddress adr = networkInterface.getInterfaceAddresses().get(0).getAddress();
                if(adr!=null) {
                    System.out.println(networkInterface.getName() + adr ); 
                }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }
}



