Monday, June 15, 2009

Wake on LAN using Java

Wake on LAN (WoL) is a standard that allows a computer to be turned on remotely by a message sent through the network.


It is platform independent technology that sends Magic Packet (containing its MAC address) to wake up computers.


When the listening computer receives this packet, the network card checks the packet for the correct information. If the Magic Packet is valid, the network card takes the computer out of hibernation or standby, or starts it up (Source: wiki).


In order for Wake on LAN to work, parts of the network interface need to stay on.


This consumes a standby power, small compared to the computer's normal operating power. If Wake on LAN is not needed, disabling it may reduce power consumption while the computer is switched off but still plugged in.
[Source: wiki]


To send magic packets in command prompt wolcmd command is used.


This is the java code to send Magic Packets to a machine provided its IP address and MAC address are available (compatible with java 1.6).



import java.io.*;
import java.net.*;

public class WakeOnLan {

public static final int PORT = 9;

public static void main(String[] args) {

String ipStr = "<>";
String macStr = "<>";
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);
DatagramSocket socket = new DatagramSocket();
socket.send(packet);
socket.close();

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

1 comment:

Cooper Bentley said...

Loovely blog you have

Total Pageviews