获取电脑物理网卡地址工具类

MacAddr.java

 

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.util.StringTokenizer;

public class MacAddr {
    //获得机器的MAC地址
    public  static String getMacAddress() throws IOException {
        String os = System.getProperty("os.name");//操作系统名称
        String macStr = "";//MAC地址
        try {
            if (os.startsWith("Windows")) {
                macStr = windowsParseMacAddress(windowsRunIpConfigCommand());
            } else if (os.startsWith("Linux")) {
                macStr = linuxParseMacAddress(linuxRunIfConfigCommand());
            } else {
                macStr = "00-00-00-00-00-00";
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }finally{
            return macStr;
        }
    }

    /**
     * TODO:linux系统,获得ipconfig 命令得到的打印信息串
     * @param ipConfigResponse String
     * @return String
     */
    private  static String linuxParseMacAddress(String ipConfigResponse){
        String localHost = null;
        try {
            localHost = InetAddress.getLocalHost().getHostAddress();
        } catch (java.net.UnknownHostException ex) {
            ex.printStackTrace();
        }

        StringTokenizer tokenizer = new StringTokenizer(ipConfigResponse, "\n");
        String lastMacAddress = null;

        while (tokenizer.hasMoreTokens()) {
            String line = tokenizer.nextToken().trim();
            boolean containsLocalHost = line.indexOf(localHost) >= 0;

            // see if line contains IP address
            if (containsLocalHost && lastMacAddress != null) {
                return lastMacAddress;
            }

            // see if line contains MAC address
            int macAddressPosition = line.indexOf("HWaddr");
            if (macAddressPosition <= 0)
                continue;

            String macAddressCandidate = line.substring(macAddressPosition + 6).trim();
            if (linuxIsMacAddress(macAddressCandidate)) {
                lastMacAddress = macAddressCandidate;
                continue;
            }
        }
        return lastMacAddress;
    }

    /**
     * TODO:判断是否为mac地址串
     * @param macAddressCandidate String
     * @return boolean
     */
    private  static boolean linuxIsMacAddress(String macAddressCandidate) {
        // TODO: use a smart regular expression
        if (macAddressCandidate.length() == 17){
            return true;
        }else{
            return false;
        }
    }

    /**
     * TODO:linux系统,获得ifconfig 命令得到的打印信息串
     * @throws IOException
     * @return String
     */
    private  static String linuxRunIfConfigCommand() throws IOException {
        Process p = Runtime.getRuntime().exec("ifconfig");
        InputStream stdoutStream = new BufferedInputStream(p.getInputStream());

        StringBuffer buffer = new StringBuffer();
        for (;;) {
            int c = stdoutStream.read();
            if (c == -1)
                break;
            buffer.append((char) c);
        }
        String outputText = buffer.toString();
        stdoutStream.close();
        return outputText;
    }

    /**
     * TODO:获得windows操作系统的MAC地址
     * @param ipConfigResponse String
     * @throws ParseException
     * @return String
     */
    private static String windowsParseMacAddress(String ipConfigResponse){
        String localHost = null;
        try {
            localHost = InetAddress.getLocalHost().getHostAddress();
        } catch (java.net.UnknownHostException ex) {
            ex.printStackTrace();
        }

        //构造一个字符串分析器,以换行符作为定界符
        StringTokenizer tokenizer = new StringTokenizer(ipConfigResponse, "\n");
        String lastMacAddress = null;

        while (tokenizer.hasMoreTokens()) {
            String line = tokenizer.nextToken().trim();
            // see if line contains IP address
            if (line.endsWith(localHost) && lastMacAddress != null) {
                return lastMacAddress;
            }
            // see if line contains MAC address
            int macAddressPosition = line.indexOf(":");
            if (macAddressPosition <= 0){
                continue;
            }

            String macAddressCandidate = line.substring(macAddressPosition + 1).trim();
            if (windowsIsMacAddress(macAddressCandidate)) {
                lastMacAddress = macAddressCandidate;
                continue;
            }
        }
        return lastMacAddress;
    }

    /**
     * TODO:判断是否为mac地址串
     * @param macAddressCandidate String
     * @return boolean
     */
    private  static boolean windowsIsMacAddress(String macAddressCandidate) {
        //mac地址格式:00-E0-4C-30-BA-01
        if (macAddressCandidate.length()==17&&macAddressCandidate.indexOf("-")>0){
            return true;
        }else{
            return false;
        }
    }
    /**
     * TODO:windows系统,获得ipconfig /all 命令得到的打印信息串
     * @throws IOException
     * @return String
     */
    private  static String windowsRunIpConfigCommand() throws IOException {
        Process p = Runtime.getRuntime().exec("ipconfig /all");
        InputStream stdoutStream = new BufferedInputStream(p.getInputStream());

        StringBuffer buffer = new StringBuffer();
        for (;;) {
            int c = stdoutStream.read();
            if (c == -1)
                break;
            buffer.append((char) c);
        }
        String outputText = buffer.toString();
        stdoutStream.close();
        return outputText;
    }

    public static void main(String[] args) {
    	try {
            System.out.println(" Operating System Name:"+ System.getProperty("os.name"));
            System.out.println(" IP/Localhost: "+ InetAddress.getLocalHost().getHostAddress());
            System.out.println(" MAC Address: " + getMacAddress());
        } catch (Throwable t) {
            t.printStackTrace();
        }
	}
}

 

你可能感兴趣的:(C++,c,linux,windows,OS)