org.cnbi.utils.license.MacAddressUtil.java Source code

Java tutorial

Introduction

Here is the source code for org.cnbi.utils.license.MacAddressUtil.java

Source

package org.cnbi.utils.license;

import java.io.*;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * ?mac??
 * 
 * @author hhl
 * 
 */
public class MacAddressUtil {
    final static Log logger = LogFactory.getLog(MacAddressUtil.class);

    /**
     * ?Mac?
     * 
     * @return
     */
    public static String getMacAddress() {
        String macAddress = "";
        // IPCHINA-4A4387B23/192.168.1.192
        try {
            InetAddress ia = InetAddress.getLocalHost();
            macAddress = getMacByIpAddress(ia);
        } catch (UnknownHostException e) {
            macAddress = getMacByCommand();
        }
        return macAddress;
    }

    /**
     * ?mac?
     * 
     * @return
     */
    private static String getMacByCommand() {
        String line = "";
        String command = "/sbin/ifconfig";

        String sOsName = System.getProperty("os.name");
        if (sOsName.startsWith("Windows")) {
            command = "ipconfig /all";
        } else {
            if ((sOsName.startsWith("Linux")) || (sOsName.startsWith("Mac")) || (sOsName.startsWith("HP-UX"))) {
                command = "/sbin/ifconfig";
            } else if (sOsName.startsWith("AIX")) {
                command = "netstat -v";
            } else {
                logger.info("The current operating system '" + sOsName + "' is not supported.");
            }
        }

        Pattern p = Pattern.compile("([a-fA-F0-9]{1,2}(-|:)){5}[a-fA-F0-9]{1,2}");
        try {
            Process pa = Runtime.getRuntime().exec(command);
            // pa.waitFor();
            BufferedReader reader = new BufferedReader(new InputStreamReader(pa.getInputStream()));

            Matcher m;
            while ((line = reader.readLine()) != null) {
                m = p.matcher(line);

                if (!m.find())
                    continue;
                line = m.group();
                break;
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return line.replaceAll("-", ":");
    }

    /**
     * IP??Mac?
     * 
     * @param ia
     * @return
     */
    private static String getMacByIpAddress(InetAddress ia) {
        // ???mac?mac?byte
        try {
            byte[] mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();
            // System.out.println("mac" + mac.length);
            // ??mac??String
            StringBuffer sb = new StringBuffer("");
            for (int i = 0; i < mac.length; i++) {
                if (i != 0) {
                    sb.append(":");
                }
                // mac[i] & 0xFF byte
                int temp = mac[i] & 0xff;
                String str = Integer.toHexString(temp);
                // System.out.println("?8?:" + str);
                if (str.length() == 1) {
                    sb.append("0" + str);
                } else {
                    sb.append(str);
                }
            }
            // ???mac?
            return sb.toString().toUpperCase();
        } catch (SocketException e) {
            e.printStackTrace();

            return getMacByCommand();
        }
    }

    /*public static void main(String[] args) {
       getMacAddress();
    }*/
}