/* * @(#)LAN.java 1.1 2003/04/24 * */ import java.net.*; import java.util.*; /** * Have a machine Wake-on-LAN * Sends the magic sequence in an UDP datagram to a machine. * The magic sequence is 6 0xFF followed by the machine's ethernet address * repeated at least 16 times. * * @author Michael John Wensley * @author Mads Bahrt * @version 2003/04/24 */ public class LAN { public static void main(String args[]) throws java.io.IOException { if (args.length >= 2) { InetAddress ia = InetAddress.getByName(args[0]); byte[] eth = ethernet(args[1]); System.out.print("Sending "); String s; for(int i = 0; i < eth.length; i++) { s = Integer.toHexString(eth[i]); while(s.length() < 2) s = "0" + s; System.out.print(s.substring(s.length() - 2)); if (i < (eth.length -1)){ System.out.print("-"); } } System.out.println(" to " + ia.getHostAddress()); wake(ia, eth); System.out.println("Sent"); } else{ System.out.println("Wake-on-lan for Java"); System.out.println("Written by Michael John Wensley and slightly modified by Mads Bahrt."); System.out.println("Usage:java LAN ipaddress|domainname macaddress"); System.out.println("Example: java LAN 192.168.1.2 00-50-BA-D1-A4-95"); System.out.println("or: java LAN someone.mydomain.tld 00-50-BA-D1-A4-95"); } //System.in.read(); // Optional - wait for a keypress before exiting } /** * Send magic packet to a computer * @param ipaddr The machine's Internet Protocol address. * @param ethernet The machine's Ethernet address. */ private static void wake(InetAddress ipaddr, byte[] ethernet) throws java.io.IOException { byte[] magic = new byte[6 + 16 * ethernet.length]; for (int i=0; i < 6; i++) magic[i] = (byte)0xff; for (int i = 6; i < magic.length; i += ethernet.length) System.arraycopy(ethernet, 0, magic, i, ethernet.length); // send it to the discard port, 9 so that the machines TCP stack will discard it. // we could send it to the echo port, 7, so that the machine returns the packet, // if it is already online. Could also ping the machine with the magic sequence as data. DatagramPacket gram = new DatagramPacket(magic, magic.length, ipaddr, 9); new DatagramSocket().send(gram); } /** * Parse an ethernet address string into its bytes. * @param address The address as hexadecimal represented bytes separated with '-' * @return The address as a byte array. */ private static byte[] ethernet(String address) { StringTokenizer parts = new StringTokenizer(address, "-"); byte[] ab = new byte[parts.countTokens()]; for(int i=0; i < ab.length; i++) ab[i] = (byte)Integer.parseInt(parts.nextToken(), 16); return ab; } }