Java获取本机IP、MAC地址、Hostname信息

package xxx;

import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.util.Enumeration;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 当前jvm运行环境机器信息
 */
public class LocalHostUtil {

	public static final String MAC;
	public static final String IP;
	public static final String HOSTNAME;
	private static final Logger LOGGER = LoggerFactory.getLogger(LocalHostUtil.class);

	static {
		String mac;
		String ip;
		String hostname;
		try {
			mac = getMacAddress();
			InetAddress addr = InetAddress.getLocalHost();
			ip = addr.getHostAddress();
			hostname = addr.getHostName();
		} catch (UnknownHostException e) {
			LOGGER.error("Can't find out address: " + e.getMessage());
			mac = "UNKNOWN";
			ip = "UNKNOWN";
			hostname = "UNKNOWN";
		} catch (Exception e) {
			LOGGER.error("Can't find out address: " + e.getMessage());
			mac = "UNKNOWN";
			ip = "UNKNOWN";
			hostname = "UNKNOWN";
		}
		OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean();
		if(!StringUtils.containsIgnoreCase(os.getName(), "windows")) {
			ip = "127.0.0.1";
		}
		if (ip.equals("127.0.0.1") || ip.equals("::1") || ip.equals("UNKNOWN")) {
			try {
				Process process = Runtime.getRuntime().exec("hostname -I");
				if (process.waitFor() == 0) {
					ip = new String(IOUtils.toByteArray(process.getInputStream()), "UTF8");
					String arr[] = ip.split(" ");
					ip = arr[0];
				}
				process = Runtime.getRuntime().exec("hostname");
				if (process.waitFor() == 0) {
					hostname = (new String(IOUtils.toByteArray(process.getInputStream()), "UTF8")).trim();
				}
			} catch (Exception e) {
				LOGGER.warn("get hostname failed {}", e.getMessage());
			}
		}
		MAC = mac;
		IP = ip;
		HOSTNAME = hostname;
	}
	
	private static String getMacAddress() throws Exception {
        Enumeration<NetworkInterface> objs = NetworkInterface.getNetworkInterfaces();
        while(objs.hasMoreElements()){
        	NetworkInterface obj = objs.nextElement();
        	if(obj == null){
        		continue;
        	}
        	byte[] bytes = obj.getHardwareAddress();
        	if(bytes == null || bytes.length != 6){
        		continue;
        	}
        	StringBuffer mac = new StringBuffer();  
        	for(byte b:bytes){
        		//与11110000作按位与运算以便读取当前字节高4位 
        		mac.append(Integer.toHexString((b&240)>>4));
        		//与00001111作按位与运算以便读取当前字节低4位
        		mac.append(Integer.toHexString(b&15));
        		mac.append(":");
        	}
        	if(mac.length()!=0){
        		String macAddr = mac.substring(0, mac.length()-1).toUpperCase();
        		LOGGER.debug("name={}, mac={}", obj.getDisplayName(), macAddr);
        		return macAddr;
        	}
        }
        throw new Exception("unkown mac");
    }
	
	public static void main(String[] args) {
		OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean();
		System.out.println(!StringUtils.containsIgnoreCase(os.getName(), "windows"));
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值