package com.mixsmart.utils;

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

/**
 * 网络相关工具类；
 * 如获取本地IP地址；MAC地址等
 * @author lmq <br />
 * 2016年12月20日
 * @version 1.0
 * @since 1.0
 */
public class NetUtils {

	private NetUtils() {
		throw new UnsupportedOperationException("NetUtils类无法实例化"); 
	}
	
	/**
	 * 获取本地IP地址
	 * @return 返回获取到的IP地址
	 */
	public static String getLocalIPv4() {
		String ip = null;
		try {
			ip = InetAddress.getLocalHost().getHostAddress();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		return ip;
	}
	
	/**
	 * 获取本地所有激活了的IP地址（不包含127.0.0.1地址）
	 * @return 返回IP数组
	 */
	public static String[] getLocalAllIPv4() {
		String[] ipArray = null;
		List<String> ips = new ArrayList<String>();
		try {
			Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
			while(nets.hasMoreElements()) {
				NetworkInterface net = nets.nextElement();
				if(net.isUp() && !net.isLoopback() && !net.isVirtual()) {
					List<InterfaceAddress> list = net.getInterfaceAddresses();
					for(InterfaceAddress interfaceAddr : list) {
						String ip = interfaceAddr.getAddress().getHostAddress();
						if(StringUtils.isNotEmpty(ip) && (ip.split("\\.")).length == 4) {
							ips.add(ip);
						}
					}
				}//if
			}//while
		} catch (SocketException e) {
			e.printStackTrace();
		}
		if(ips.size()>0) {
			ipArray = new String[ips.size()];
			ips.toArray(ipArray);
		}
		return ipArray;
	}
	
	/**
	 * 获取本地所有MAC
	 * @return 返回MAC数组
	 */
	public static String[] getLocalAllMac() {
		String[] macArray = null;
		List<String> macList = new ArrayList<String>();
		try {
			Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
			while(nets.hasMoreElements()) {
				NetworkInterface net = nets.nextElement();
				if(net.isUp() && !net.isLoopback() && !net.isVirtual()) {
					byte[] macBytes = net.getHardwareAddress();
					StringBuilder sb = new StringBuilder();
					for(int i= 0; i<macBytes.length; i++) {
						if(i != 0 ) {
							sb.append("-");
						}
						//字节转换为整数
						int temp = macBytes[i] & 0xff;
						String str = Integer.toHexString(temp);
						if(str.length() == 1) {
							sb.append("0" + str);
						} else {
							sb.append(str);
						}
					}//for
					macList.add(sb.toString().toUpperCase());
				}//if
			}//while
		} catch (SocketException e) {
			e.printStackTrace();
		}
		if(macList.size()>0) {
			macArray = new String[macList.size()];
			macList.toArray(macArray);
		}
		return macArray;
	}
}
