Android Wake On Lan

时间:2012-10-23 13:43:02

标签: android android-networking wake-on-lan

我正在尝试编写一个会唤醒我的电脑的应用。我认为我有解决方案,但由于某种原因它无法正常工作。

下面的脚本是一个类。多数民众赞成使用主要活动中的mac和broadcastip:

Wake.wakeup(broadcastIP, mac);


public class Wake {

BroadcastIP和mac将是字符串。

    public static void wakeup(String broadcastIP, String mac) {
        if (mac == null) {
            return;
        }

包装应该计算好。

        try {
            byte[] macBytes = getMacBytes(mac);
            byte[] bytes = new byte[6 + 16 * macBytes.length];
            for (int i = 0; i < 6; i++) {
                bytes[i] = (byte) 0xff;
            }
            for (int i = 6; i < bytes.length; i += macBytes.length) {
                System.arraycopy(macBytes, 0, bytes, i, macBytes.length);
            }

            InetAddress address = InetAddress.getByName(broadcastIP);
            DatagramPacket packet = new DatagramPacket(bytes, bytes.length, address, 9);
            DatagramSocket socket = new DatagramSocket();
            socket.send(packet);
            socket.close();

        }
        catch (Exception e) {
        }
    }

从mac转换应该很好。这是在唤醒意图时调用的。

    private static byte[] getMacBytes(String macStr) throws IllegalArgumentException {
        byte[] bytes = new byte[6];
        if (macStr.length() != 12)
        {
            throw new IllegalArgumentException("Invalid MAC address...");
        }
        try {
            String hex;
            for (int i = 0; i < 6; i++) {
                hex = macStr.substring(i*2, i*2+2);
                bytes[i] = (byte) Integer.parseInt(hex, 16);
            }
        }
        catch (NumberFormatException e) {
            throw new IllegalArgumentException("Invalid hex digit...");
        }
        return bytes;
    }

}

我感谢你能给我的每一个帮助/暗示。

0 个答案:

没有答案
相关问题