license.mac.MacTest.java Source code

Java tutorial

Introduction

Here is the source code for license.mac.MacTest.java

Source

package license.mac;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.codec.binary.Base64;

/**
 * mac?
 * @author byht
 *
 */
public class MacTest {

    public static void main(String[] args) throws Exception {
        Map<Integer, String> infoMap = new HashMap<Integer, String>();
        infoMap.put(1, "");
        infoMap.put(2, "");
        infoMap.put(2, "");
        infoMap.put(2, "");
        infoMap.put(12, "eth0");

        MacTest mac = new MacTest();

        System.out.println();
        System.out.println();
        System.out.println("************?mac?*********");
        System.out.println();
        System.out.println();
        InetAddress ia = InetAddress.getLocalHost();//?IP
        System.out.println("IP .........: " + ia.getHostAddress());
        System.out.println("MAC .........: " + getMACAddress(ia));

        System.out.println();
        System.out.println();
        mac.checkMac();
    }

    //?MAC?
    private static String getMACAddress(InetAddress ia) throws Exception {
        //???mac?mac?byte
        byte[] mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();

        //??mac??String
        StringBuffer sb = new StringBuffer();

        for (int i = 0; i < mac.length; i++) {
            if (i != 0) {
                sb.append("-");
            }
            //mac[i] & 0xFF byte
            String s = Integer.toHexString(mac[i] & 0xFF);
            sb.append(s.length() == 1 ? 0 + s : s);
        }

        //???mac?
        return sb.toString().toUpperCase();
    }

    /**
     * mac?
     * @return
     * @throws SocketException
     */
    public boolean checkMac() throws SocketException {
        StringBuffer sb = new StringBuffer();
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        int i = 12;
        Base64 base64 = new Base64();
        for (NetworkInterface ni : Collections.list(interfaces)) {
            if (ni.getName().substring(0, 1).equalsIgnoreCase("e")) {
                sb.append(String.valueOf(i)).append('=').append(ni.getName()).append('\n');
                i++;
                byte[] mac = ni.getHardwareAddress();
                sb.append(String.valueOf(i)).append('=').append(base64.encodeAsString(mac)).append('\n');
                i++;
            }
        }
        System.out.println(sb.toString());
        return true;
    }

}