get Mac Address from shell command - Java Network

Java examples for Network:Mac Address

Description

get Mac Address from shell command

Demo Code


//package com.java2s;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {


    public static String getMacAddr(String commond, String newLine) {
        if (commond == null)
            return "Bad Commond!";
        String os = getOSName();// ww w  .ja va 2s  .c  o  m
        if (os.startsWith("windows")) {
            return Window(commond, newLine);
        } else {
            return Linux(commond, newLine);
        }
    }

    private static String getOSName() {
        return System.getProperty("os.name").toLowerCase();
    }

    private static String Window(String commond, String newLine) {
        BufferedReader bufferedReader = null;
        Process process = null;
        try {
            process = Runtime.getRuntime().exec(commond);  
            bufferedReader = new BufferedReader(new InputStreamReader(
                    process.getInputStream()));
            String line = null;
            StringBuffer tmp = new StringBuffer();
            while ((line = bufferedReader.readLine()) != null) {
                tmp.append(line).append(newLine);
            }
            return tmp.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            bufferedReader = null;
            process = null;
        }
        return "Bad Commond!";
    }

    private static String Linux(String commond, String newLine) {
        BufferedReader bufferedReader = null;
        Process process = null;
        try {
            process = Runtime.getRuntime().exec(commond);
            bufferedReader = new BufferedReader(new InputStreamReader(
                    process.getInputStream()));
            String line = null;
            StringBuffer tmp = new StringBuffer();
            while ((line = bufferedReader.readLine()) != null) {
                tmp.append(line).append(newLine);
            }
            return tmp.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            bufferedReader = null;
            process = null;
        }

        return "Bad Commond!";
    }
}

Related Tutorials