/* * WakeOnLan.java * Copyright (C) 2011,2012 Wannes De Smet * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.xenmaster.connectivity; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import org.apache.log4j.Logger; /** * * @created Oct 8, 2011 * @author double-u */ public class WakeOnLan { // WOL functionality from http://www.jibble.org/wake-on-lan/ public static boolean wakeHost(String ipAddress, String macAddress, boolean confirmHostIsUp) { try { byte[] macBytes = getMacBytes(macAddress); 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(ipAddress); DatagramPacket packet = new DatagramPacket(bytes, bytes.length, address, 9); DatagramSocket socket = new DatagramSocket(); socket.send(packet); socket.close(); Logger.getLogger(WakeOnLan.class).info("Wake on LAN packet sent to " + ipAddress); if (!confirmHostIsUp) { return true; } return address.isReachable(10000); } catch (IllegalArgumentException | IOException e) { Logger.getLogger(WakeOnLan.class).error(e); } return false; } 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; } }