get OS MAC Address - Java Network

Java examples for Network:Mac Address

Description

get OS MAC Address

Demo Code


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

public class Main {

    public static String getOSMACAddress() {
        String mac = null;//  ww w .  j  a  va  2 s. com
        BufferedReader bufferedReader = null;
        Process process = null;
        try {
            process = Runtime.getRuntime().exec("/sbin/ifconfig en0");
            // linuxeth0? mac
            bufferedReader = new BufferedReader(new InputStreamReader(
                    process.getInputStream(), "utf-8"));
            String line = null;
            int index = -1;
            while ((line = bufferedReader.readLine()) != null) {
                index = line.toLowerCase().indexOf("ether");// ?[hwaddr]
                if (index >= 0) {// ?
                    mac = line.substring(index + "ether".length() + 1)
                            .trim();
                    // mac?2?
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            bufferedReader = null;
            process = null;
        }
        return mac;
    }
}

Related Tutorials