package cz.vutbr.feec.session.common;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * The Class NetUtils.
 */
public class NetUtils {
	
	/**
	 * Return ip number of interface.
	 * 
	 * @param ifNumber number of possition of iface.
	 * 
	 * @return the local address
	 */
	public static InetAddress getLocalAddress(int ifNumber) {
		try {
			Enumeration<NetworkInterface> eNI = NetworkInterface
					.getNetworkInterfaces();

			NetworkInterface cNI;
			Enumeration<InetAddress> eIA;
			InetAddress cIA = null;
			
			
			
			for (; eNI.hasMoreElements();) {
				cNI = eNI.nextElement();
				eIA = cNI.getInetAddresses();
				int counter = 1;
				for (; eIA.hasMoreElements();) {
					cIA = eIA.nextElement();
					if(counter == ifNumber) {
//						return cIA.getHostAddress();
						return cIA;
					}
					counter++;
				}
			}

			return cIA;
		} catch (SocketException eS) {
			System.out.println("ERROR - SocketException");
			System.out.println("ERROR - " + eS.getLocalizedMessage());
			eS.printStackTrace();
			System.exit(2);
			return null;
		}
	}
	
	/**
	 * Gets the local address string.
	 * 
	 * @param pozition the pozition
	 * 
	 * @return the local address string
	 */
	public static String getLocalAddressString(int pozition) {
		String str = getLocalAddress(2).toString();
		return str.substring(1, str.length());
	}
	
	/**
	 * Convert addr.
	 * 
	 * @param addr the addr
	 * 
	 * @return the string
	 */
	public static String convertAddr(byte[] addr) {
		return ""+(addr[0]&0xff)+"."+(addr[1]&0xff)+"."
			+(addr[2]&0xff)+"."+(addr[3]&0xff);
	}
	
	/**
	 * Gets the local address byte.
	 * 
	 * @return the local address byte
	 */
	public static byte[] getLocalAddressByte() {
		return getLocalAddress(2).getAddress();
	}
	
	
	
	/**
	 * The main method.
	 * 
	 * @param args the args
	 */
	public static void main(String[] args) {
		System.out.println(NetUtils.getLocalAddressString(2));
		byte[] b = NetUtils.getLocalAddressByte();
		System.out.println(NetUtils.convertAddr(b));
		
	}
}
