Skip to content

Instantly share code, notes, and snippets.

@Nithanim
Created May 1, 2019 15:26
Show Gist options
  • Save Nithanim/324b385d52472b66a7af43b609a1de6f to your computer and use it in GitHub Desktop.
Save Nithanim/324b385d52472b66a7af43b609a1de6f to your computer and use it in GitHub Desktop.
Simple WoL (Wake on Lan) in Java
package me.nithanim.test.wol;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
public class Main {
public static void main(String[] args) throws IOException {
// 0B-5A-70-78-C0-D6
long mac = 0x0B5A7078C0D6L;
new Main().sendWol(mac);
}
public void sendWol(long mac) throws IOException {
byte[] data = buildPacket(mac);
sendPacket(data);
}
private byte[] buildPacket(long mac) {
byte[] data = new byte[(1 + 16) * 6];
writeArrayPart(data, 0, 0xFFFFFFFFFFFFL);
for (int i = 1; i <= 16; i++) {
writeArrayPart(data, i, mac);
}
return data;
}
private void writeArrayPart(byte[] data, int idx, long value) {
int offset = idx * 6;
data[offset + 0] = (byte) (value >>> (8 * 5));
data[offset + 1] = (byte) (value >>> (8 * 4));
data[offset + 2] = (byte) (value >>> (8 * 3));
data[offset + 3] = (byte) (value >>> (8 * 2));
data[offset + 4] = (byte) (value >>> (8 * 1));
data[offset + 5] = (byte) (value >>> (8 * 0));
}
private void sendPacket(byte[] data) throws IOException {
try (DatagramSocket socket = new DatagramSocket()) {
// binding the socket to ports < 1024 not possible, but sending works
DatagramPacket packet = new DatagramPacket(data, data.length, new InetSocketAddress("255.255.255.255", 9));
socket.send(packet);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment