9

My Android app sends/retrieves data to/from the user's own PC using HTTP and it's working fine with a handful of beta testers. I now need to consider a situation where the PC is hibernating.

I've never done this before but I've googled to find info about the WOL 'magic packet' and some simple source written in C (using CAsyncSocket at the client end). Doing this over a wi-fi connection on the user's home network is likely to be relatively straight-forward but ideally I want this to work over mobile internet (assuming the user can configure their home router to accept / forward the packet).

I'm guessing I need to use some generic Java network code and I've been looking at java.net.

At this point I can't decide whether I should be using java.net.Socket or java.net.DatagramSocket. So the question is, am I approaching this the right way and which of the two socket types should I be using (or would both suffice)? Many thanks.

Squonk
  • 48,735
  • 19
  • 103
  • 135
  • from what I remember, it can be anything: UDP, ICMP, TCP as long as the magic is in the packet, but datagram should be easier to program. the hard part will be to find a way to make it work over wifi; it's pretty reliable on wired networks though. – jcomeau_ictx Apr 15 '11 at 21:07
  • Ive used several apps in the market store to wake my computer up using WOL over wifi when connected to my home network. I didn't have much luck doing it over the net since I failed to configure my router correctly since it didn't forward the packet to the computer behind Nat. – Bear Apr 15 '11 at 21:31

3 Answers3

14

I can't take too much credit for it as its from this site

But this is a java version of wake on lan class:

public static final int PORT = 9;    

public static void main(String[] args) {
    
    if (args.length != 2) {
        System.out.println("Usage: java WakeOnLan <broadcast-ip> <mac-address>");
        System.out.println("Example: java WakeOnLan 192.168.0.255 00:0D:61:08:22:4A");
        System.out.println("Example: java WakeOnLan 192.168.0.255 00-0D-61-08-22-4A");
        System.exit(1);
    }
    
    String ipStr = args[0];
    String macStr = args[1];
    
    try {
        byte[] macBytes = getMacBytes(macStr);
        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(ipStr);
        DatagramPacket packet = new DatagramPacket(bytes, bytes.length, address, PORT);
        try (DatagramSocket socket = new DatagramSocket()) {
            socket.send(packet);
        }
        
        System.out.println("Wake-on-LAN packet sent.");
    }
    catch (Exception e) {
        System.out.println("Failed to send Wake-on-LAN packet: " + e);
        System.exit(1);
    }
    
}

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

Of course you will need to modify this to work with android (very little work needed) but I found it works better than @Bear's answer.

Manuel
  • 649
  • 8
  • 13
Chris.Jenkins
  • 13,051
  • 4
  • 60
  • 61
  • Thanks. I was able to get Bear's example to work but I might try the code you posted to compare the two. – Squonk Dec 01 '12 at 00:58
  • What I would note also, I had issues with port 9 on OSX 10.8, I had to use the echo port (7) to get the Mac to wake. – Chris.Jenkins Dec 04 '12 at 22:21
  • I'm only wondering why this works no matter which port I use..? Works with port 7, 9, 11999, whatever.. – tkit Jan 11 '14 at 12:13
  • @pootzko I think it depends in implementation, OSx/Windows/*nix all different, Port 9 worked on Windows 8 when we tested but, 7 worked for OSx and Windows. Was a mere observation. – Chris.Jenkins Jan 13 '14 at 11:34
11

Here is some C# code that I have used in the past. It should be relatively easy to convert into java and send using a DatagramPacket

namespace WakeOnLan
{
    class Program
    {
        static void Main(string[] args)
        {

            byte[] mac = new byte[] { mac address goes here i.e 0x00, and so on };
            WakeUp(mac);
        }

        private static void WakeUp(byte[] mac)
        {
            //
            // WOL packet is sent over UDP 255.255.255.0:40000.
            //
            Console.WriteLine("Waking Up.......");
            UdpClient client = new UdpClient();
            client.Connect(IPAddress.Broadcast, 40000);

            //
            // WOL packet contains a 6-bytes trailer and 16 times a 6-bytes sequence containing the MAC address.
            //
            byte[] packet = new byte[17 * 6];

            //
            // Trailer of 6 times 0xFF.
            //
            for (int i = 0; i < 6; i++)
                packet[i] = 0xFF;

            //
            // Body of magic packet contains 16 times the MAC address.
            //
            for (int i = 1; i <= 16; i++)
                for (int j = 0; j < 6; j++)
                    packet[i * 6 + j] = mac[j];

            //
            // Submit WOL packet.
            //
            client.Send(packet, packet.Length);
            Console.WriteLine("Machine Woke Up....");
        }
    }
}

Hope this helps

Josh Lee
  • 171,072
  • 38
  • 269
  • 275
Bear
  • 1,541
  • 3
  • 20
  • 32
  • Thanks. Your code example is similar to the C code I found but slightly more concise. It didn't take much to convert to Java and I was able to translate the UdpClient parts of the code to a DatagramSocket with only a few extra lines. – Squonk Apr 16 '11 at 02:53
2

java.net.DatagramSocket would probably work well enough, since WoL does not provide delivery confirmation. It's doubtful you'll be able to get it to work outside the local network, since WoL packets are broadcast across the network with the destination address as the MAC address of the target computer and most routers are setup to block broadcast packets from the WAN.

Justin Pearce
  • 4,994
  • 2
  • 24
  • 37
  • Thanks for your response. I've got this working for my LAN with a Java version of Bear's code. I think I may be able to get this to work from outside by using port forwarding but I haven't tested it yet. I'll see what happens. – Squonk Apr 16 '11 at 03:11