Java Mac Address Get getMACAddress()

Here you can find the source of getMACAddress()

Description

Tries to determine the MAC address of the machine Kettle is running on.

License

Apache License

Return

The MAC address.

Declaration

public static final String getMACAddress() throws Exception 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.net.InetAddress;

import java.net.NetworkInterface;
import java.net.SocketException;

import java.util.Enumeration;

import java.util.Properties;

public class Main {
    private static Properties properts;

    /**/*from   w w  w .  ja v  a2s .c  o  m*/
     * Tries to determine the MAC address of the machine Kettle is running on.
     * 
     * @return The MAC address.
     */
    public static final String getMACAddress() throws Exception {
        String ip = getIPAddress();
        String mac = "none";
        String os = getOS();
        String s = "";

        // System.out.println("os = "+os+", ip="+ip);

        if (os.equalsIgnoreCase("Windows NT") || os.equalsIgnoreCase("Windows 2000")
                || os.equalsIgnoreCase("Windows XP") || os.equalsIgnoreCase("Windows 95")
                || os.equalsIgnoreCase("Windows 98") || os.equalsIgnoreCase("Windows Me")
                || os.startsWith("Windows")) {
            try {
                // System.out.println("EXEC> nbtstat -a "+ip);

                Process p = Runtime.getRuntime().exec("nbtstat -a " + ip);

                // read the standard output of the command
                BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));

                while (!procDone(p)) {
                    while ((s = stdInput.readLine()) != null) {
                        // System.out.println("NBTSTAT> "+s);
                        if (s.indexOf("MAC") >= 0) {
                            int idx = s.indexOf('=');
                            mac = s.substring(idx + 2);
                        }
                    }
                }
                stdInput.close();
            } catch (Exception e) {

            }
        } else if (os.equalsIgnoreCase("Linux")) {
            try {
                Process p = Runtime.getRuntime().exec("/sbin/ifconfig -a");

                // read the standard output of the command
                BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));

                while (!procDone(p)) {
                    while ((s = stdInput.readLine()) != null) {
                        int idx = s.indexOf("HWaddr");
                        if (idx >= 0) {
                            mac = s.substring(idx + 7);
                        }
                    }
                }
                stdInput.close();
            } catch (Exception e) {

            }
        } else if (os.equalsIgnoreCase("Solaris")) {
            try {
                Process p = Runtime.getRuntime().exec("/usr/sbin/ifconfig -a");

                // read the standard output of the command
                BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));

                while (!procDone(p)) {
                    while ((s = stdInput.readLine()) != null) {
                        int idx = s.indexOf("ether");
                        if (idx >= 0) {
                            mac = s.substring(idx + 6);
                        }
                    }
                }
                stdInput.close();
            } catch (Exception e) {

            }
        } else if (os.equalsIgnoreCase("HP-UX")) {
            try {
                Process p = Runtime.getRuntime().exec("/usr/sbin/lanscan -a");

                // read the standard output of the command
                BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));

                while (!procDone(p)) {
                    while ((s = stdInput.readLine()) != null) {
                        if (s.indexOf("MAC") >= 0) {
                            int idx = s.indexOf("0x");
                            mac = s.substring(idx + 2);
                        }
                    }
                }
                stdInput.close();
            } catch (Exception e) {

            }
        }

        return trim(mac);
    }

    /**
     * Determins the IP address of the machine Kettle is running on.
     * 
     * @return The IP address
     */
    public static final String getIPAddress() throws Exception {
        Enumeration<NetworkInterface> enumInterfaces = NetworkInterface.getNetworkInterfaces();
        while (enumInterfaces.hasMoreElements()) {
            NetworkInterface nwi = (NetworkInterface) enumInterfaces.nextElement();
            Enumeration<InetAddress> ip = nwi.getInetAddresses();
            while (ip.hasMoreElements()) {
                InetAddress in = (InetAddress) ip.nextElement();
                if (!in.isLoopbackAddress() && in.toString().indexOf(":") < 0) {
                    return in.getHostAddress();
                }
            }
        }
        return "127.0.0.1";
    }

    /**
     * Get the primary IP address tied to a network interface (excluding
     * loop-back etc)
     * 
     * @param networkInterfaceName
     *            the name of the network interface to interrogate
     * @return null if the network interface or address wasn't found.
     * 
     * @throws SocketException
     *             in case of a security or network error
     */
    public static final String getIPAddress(String networkInterfaceName) throws SocketException {
        NetworkInterface networkInterface = NetworkInterface.getByName(networkInterfaceName);
        Enumeration<InetAddress> ipAddresses = networkInterface.getInetAddresses();
        while (ipAddresses.hasMoreElements()) {
            InetAddress inetAddress = (InetAddress) ipAddresses.nextElement();
            if (!inetAddress.isLoopbackAddress() && inetAddress.toString().indexOf(":") < 0) {
                String hostname = inetAddress.getHostAddress();
                return hostname;
            }
        }
        return null;
    }

    /**
    * determine the OS name
    * 
    * @return The name of the OS
    */
    public static final String getOS() {
        return System.getProperty("os.name");
    }

    private static final boolean procDone(Process p) {
        try {
            p.exitValue();
            return true;
        } catch (IllegalThreadStateException e) {
            return false;
        }
    }

    /**
     * Trims a string: removes the leading and trailing spaces of a String.
     * 
     * @param str
     *            The string to trim
     * @return The trimmed string.
     */
    public static final String trim(String str) {
        if (str == null)
            return null;

        int max = str.length() - 1;
        int min = 0;

        while (min <= max && isSpace(str.charAt(min)))
            min++;
        while (max >= 0 && isSpace(str.charAt(max)))
            max--;

        if (max < min)
            return "";

        return str.substring(min, max + 1);
    }

    public static String getProperty(String pro) {
        return getProperty(pro, true);
    }

    public static String getProperty(String pro, String defaultValue) {
        return getProperty(pro, defaultValue, true);
    }

    public static String getProperty(String pro, boolean trim) {
        String value = null;
        if (properts != null)
            value = (String) properts.get(pro);
        if (value != null && trim)
            value = value.trim();
        return value;
    }

    public static String getProperty(String pro, String defaultValue, boolean trim) {
        String value = null;
        if (properts != null)
            value = (String) properts.get(pro);
        if (value == null)
            return defaultValue;
        else {
            if (trim)
                value = value.trim();
        }
        return value;
    }

    /**
     * Determines whether or not a character is considered a space. A character
     * is considered a space in Kettle if it is a space, a tab, a newline or a
     * cariage return.
     * 
     * @param c
     *            The character to verify if it is a space.
     * @return true if the character is a space. false otherwise.
     */
    public static final boolean isSpace(char c) {
        return c == ' ' || c == '\t' || c == '\r' || c == '\n';
    }
}

Related

  1. getMACAddress()
  2. getMacAddress()
  3. getMacAddress()
  4. getMacAddress()
  5. getMacAddress()
  6. getMacAddress()
  7. getMacAddress()
  8. getMacAddress()
  9. getMacAddress()