Android 获取本机IP、Mac、名称

获取IP

public String getLocalIpAddress() {
    try {
        Enumeration en = NetworkInterface.getNetworkInterfaces();
        for (; en.hasMoreElements();) {
            NetworkInterface intf = (NetworkInterface) en.nextElement();
            for (Enumeration enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                InetAddress inetAddress = (InetAddress) enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress() && !inetAddress.isLinkLocalAddress()) {
                    return inetAddress.getHostAddress().toString();
                }
            }
        }
    } catch (SocketException ex) {
        Toast.makeText(getActivity(), ex.getMessage(),Toast.LENGTH_SHORT).show();
    }

    return null;
}

获取MAC

public String getLocalMacAddressFromIp(Context context) {
    String mac_s = "";
    try {
        byte[] mac;
        NetworkInterface ne = NetworkInterface.getByInetAddress(InetAddress.getByName(getLocalIpAddress()));
        mac = ne.getHardwareAddress();
        mac_s = byte2hex(mac);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return mac_s;
}

public String byte2hex(byte[] b) {
    StringBuffer hs = new StringBuffer(b.length);
    String stmp = "";
    int len = b.length;
    for (int n = 0; n < len; n++) {
        stmp = Integer.toHexString(b[n] & 0xFF); /
        if (stmp.length() == 1) {
            hs = hs.append("0").append(stmp);
        } else {
            hs = hs.append(stmp);
        }
    }

    return String.valueOf(hs);
}

获取名称

basePadName.setText(android.os.Build.MANUFACTURER);

你可能感兴趣的:(Android 获取本机IP、Mac、名称)