Thursday, October 1, 2009

[Java] Wake on LAN

On PC di rumah dari ofis adalah idaman aku sekian lama. Dan aku rase aku memang 'n00b' giler sebab baru tau pasal wake on LAN. Jadi tak salah rasenye aku post bende ni untuk panduan aku (kalau save dalam PC confirm tak jumpe cari).

Wake on Lan adalah cara 'on'kan PC remotely dengan menghantar simple UDP packet ke port 9 kat NIC yg support Wake on LAN. Nak tau support ke tak biasenye LED kat LAN socket tu masih menyala walaupun PC dah turn off. Untuk anta packet tu, leh pkai ape2 pun coding n ni aku nak share coding Java:


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

public class WakeOnLan {

public static final int PORT = 9;

public static void main(String[] args) {

if (args.length != 2) {
System.out.println("Usage: java WakeOnLan ");
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 <>
bytes[i] = (byte) 0xff;
}
for (int i = 6; i <>
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 <>
bytes[i] = (byte) Integer.parseInt(hex[i], 16);
}
}
catch (NumberFormatException e) {
throw new IllegalArgumentException("Invalid hex digit in MAC address.");
}
return bytes;
}


}


lepas compile code ni, run code ni dengan due argument tambahan: ip adress n MAC address.
contoh:

java WakeOnLan 192.168.0.20 00:0D:61:08:22:4A

tu saja.. kalau tak success, antar 2, 3 kali sebab UDP ni maklum la.

p/s: kalau PC kat umah tu behind firewall, jgn lupe allow port 9 n jagn lupe port forwarding port 9 ke ip pc kite tu. maknenye, mase run java tu, letak ip luar (WAN IP) pastu kat firewall or adsl router tu foward port 9 ke LAN ip PC kite. (aku taktau la ape instilah sebenar ip luar tu..duhh)

No comments: