Android Wake On Lan

723 Views Asked by At

I'm trying to write an app that will wake up my computer. I think I have the solution but for some reason its not working.

The script below is one class. Thats called with the mac and broadcastip from the mainactivity:

Wake.wakeup(broadcastIP, mac);


public class Wake {

BroadcastIP and mac will be strings.

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

The package should be calculated good.

        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) {
        }
    }

The conversion from the mac should be good to. This is called when the wakeup is intented.

    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;
    }

}

I appreciate every help/hint you can give me.

0

There are 0 best solutions below