Last active
December 15, 2015 14:59
-
-
Save filewalkwithme/5278433 to your computer and use it in GitHub Desktop.
Java Class for Wake On Lan
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* maiconio | |
* http://pistach.es/ | |
*/ | |
import java.io.IOException; | |
import java.net.DatagramPacket; | |
import java.net.DatagramSocket; | |
import java.net.InetSocketAddress; | |
import java.net.SocketException; | |
public class WakeOnLan { | |
/** | |
* @param args | |
*/ | |
public static void main(String[] args) { | |
if (args.length != 2){ | |
System.out.println("Usage: java WakeOnLan 12:34:56:78:90:AB 255.255.255.255"); | |
System.exit(0); | |
} | |
String macDest = args[0].toUpperCase(); //"12:34:56:78:90:AB"; | |
String ipDest = args[1]; //"255.255.255.255"; | |
int port = 9; | |
DatagramSocket datagramSocket; | |
try { | |
datagramSocket = new DatagramSocket(port); | |
datagramSocket.setBroadcast(true); | |
String[] macPositions = macDest.split(":"); | |
byte[] macPositionsBuf = new byte[macPositions.length]; | |
for (int i=0; i< macPositions.length; i++){ | |
macPositionsBuf[i] = (byte) ((int) Integer.decode("0x"+macPositions[i])); | |
} | |
byte[] buf = new byte[6 + ((macPositionsBuf.length) * 16)]; | |
for (int i=0; i < 6; i++){ | |
buf[i] = (byte) 0xFF; | |
} | |
for (int i=0; i<16; i++){ | |
System.arraycopy(macPositionsBuf, 0, buf, (i*macPositionsBuf.length) + 6, macPositionsBuf.length); | |
} | |
InetSocketAddress inetSocketAddress = new InetSocketAddress(ipDest, 9); | |
DatagramPacket p = new DatagramPacket(buf, buf.length, inetSocketAddress); | |
datagramSocket.send(p); | |
System.out.println("Magic packet sent!"); | |
} catch (SocketException e) { | |
System.err.println("An error occurred while initializing the socket."); | |
e.printStackTrace(); | |
} catch (IOException e) { | |
System.err.println("An error occurred while sending the magic packet!"); | |
e.printStackTrace(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment