如何使用Android获取MAC地址 - jmdns

时间:2015-07-27 12:04:12

标签: android bonjour jmdns

我需要获取特定设备的Mac-Address。我正在使用Android-jmdns服务来扫描设备并获取IP地址,现在我需要获取特定设备的Mac-Address。我们可以使用Mac-使用Android获取IP地址时的地址 - jmdns服务或任何其他方式获取带有IP地址的Mac地址?

1 个答案:

答案 0 :(得分:1)

您需要 AndroidManifest.xml

中的此权限
// AndroidManifest.xml permissions
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.UPDATE_DEVICE_STATS"></uses-permission>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>

您可以尝试拳头解决方案

WifiManager wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);

if(wifiManager.isWifiEnabled()) {
    // WIFI ALREADY ENABLED. GRAB THE MAC ADDRESS HERE
    WifiInfo info = wifiManager.getConnectionInfo();
    String address = info.getMacAddress();
} else {
    // ENABLE THE WIFI FIRST
    wifiManager.setWifiEnabled(true);

    // WIFI IS NOW ENABLED. GRAB THE MAC ADDRESS HERE
    WifiInfo info = wifiManager.getConnectionInfo();
    String address = info.getMacAddress();
}

第二个

// test functions
Utils.getMACAddress("wlan0");
Utils.getMACAddress("eth0");
Utils.getIPAddress(true); // IPv4
Utils.getIPAddress(false); // IPv6 

Utils.java

import java.io.*;
import java.net.*;
import java.util.*;   
import org.apache.http.conn.util.InetAddressUtils;

    public class Utils {

        /**
         * Convert byte array to hex string
         * @param bytes
         * @return
         */
        public static String bytesToHex(byte[] bytes) {
            StringBuilder sbuf = new StringBuilder();
            for(int idx=0; idx < bytes.length; idx++) {
                int intVal = bytes[idx] & 0xff;
                if (intVal < 0x10) sbuf.append("0");
                sbuf.append(Integer.toHexString(intVal).toUpperCase());
            }
            return sbuf.toString();
        }

        /**
         * Get utf8 byte array.
         * @param str
         * @return  array of NULL if error was found
         */
        public static byte[] getUTF8Bytes(String str) {
            try { return str.getBytes("UTF-8"); } catch (Exception ex) { return null; }
        }

        /**
         * Load UTF8withBOM or any ansi text file.
         * @param filename
         * @return  
         * @throws java.io.IOException
         */
        public static String loadFileAsString(String filename) throws java.io.IOException {
            final int BUFLEN=1024;
            BufferedInputStream is = new BufferedInputStream(new FileInputStream(filename), BUFLEN);
            try {
                ByteArrayOutputStream baos = new ByteArrayOutputStream(BUFLEN);
                byte[] bytes = new byte[BUFLEN];
                boolean isUTF8=false;
                int read,count=0;           
                while((read=is.read(bytes)) != -1) {
                    if (count==0 && bytes[0]==(byte)0xEF && bytes[1]==(byte)0xBB && bytes[2]==(byte)0xBF ) {
                        isUTF8=true;
                        baos.write(bytes, 3, read-3); // drop UTF8 bom marker
                    } else {
                        baos.write(bytes, 0, read);
                    }
                    count+=read;
                }
                return isUTF8 ? new String(baos.toByteArray(), "UTF-8") : new String(baos.toByteArray());
            } finally {
                try{ is.close(); } catch(Exception ex){} 
            }
        }

        /**
         * Returns MAC address of the given interface name.
         * @param interfaceName eth0, wlan0 or NULL=use first interface 
         * @return  mac address or empty string
         */
        public static String getMACAddress(String interfaceName) {
            try {
                List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
                for (NetworkInterface intf : interfaces) {
                    if (interfaceName != null) {
                        if (!intf.getName().equalsIgnoreCase(interfaceName)) continue;
                    }
                    byte[] mac = intf.getHardwareAddress();
                    if (mac==null) return "";
                    StringBuilder buf = new StringBuilder();
                    for (int idx=0; idx<mac.length; idx++)
                        buf.append(String.format("%02X:", mac[idx]));       
                    if (buf.length()>0) buf.deleteCharAt(buf.length()-1);
                    return buf.toString();
                }
            } catch (Exception ex) { } // for now eat exceptions
            return "";
            /*try {
                // this is so Linux hack
                return loadFileAsString("/sys/class/net/" +interfaceName + "/address").toUpperCase().trim();
            } catch (IOException ex) {
                return null;
            }*/
        }

        /**
         * Get IP address from first non-localhost interface
         * @param ipv4  true=return ipv4, false=return ipv6
         * @return  address or empty string
         */
        public static String getIPAddress(boolean useIPv4) {
            try {
                List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
                for (NetworkInterface intf : interfaces) {
                    List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
                    for (InetAddress addr : addrs) {
                        if (!addr.isLoopbackAddress()) {
                            String sAddr = addr.getHostAddress().toUpperCase();
                            boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr); 
                            if (useIPv4) {
                                if (isIPv4) 
                                    return sAddr;
                            } else {
                                if (!isIPv4) {
                                    int delim = sAddr.indexOf('%'); // drop ip6 port suffix
                                    return delim<0 ? sAddr : sAddr.substring(0, delim);
                                }
                            }
                        }
                    }
                }
            } catch (Exception ex) { } // for now eat exceptions
            return "";
        }

    }

可能重复:

How to find MAC address of an Android device programmatically

How to get IP address of the device from code?