|
| 1 | +package com.em7.wol.service; |
| 2 | + |
| 3 | +import lombok.RequiredArgsConstructor; |
| 4 | +import lombok.extern.slf4j.Slf4j; |
| 5 | +import org.springframework.stereotype.Service; |
| 6 | + |
| 7 | +import java.net.DatagramPacket; |
| 8 | +import java.net.DatagramSocket; |
| 9 | +import java.net.InetAddress; |
| 10 | + |
| 11 | +import static com.em7.wol.service.WakeStrategy.BROADCAST_TO_IP; |
| 12 | + |
| 13 | +@Slf4j |
| 14 | +@Service |
| 15 | +@RequiredArgsConstructor |
| 16 | +public class WakeServiceImpl implements WakeService { |
| 17 | + |
| 18 | + private final WakeStrategy wakeStrategy = BROADCAST_TO_IP; |
| 19 | + |
| 20 | + @Override |
| 21 | + public void sendMagicPacket(String ipStr, String macStr) { |
| 22 | + try { |
| 23 | + final byte[] macBytes = getMacBytes(macStr); |
| 24 | + final byte[] bytes = new byte[6 + 16 * macBytes.length]; |
| 25 | + for (int i = 0; i < 6; i++) { |
| 26 | + bytes[i] = (byte) 0xff; |
| 27 | + } |
| 28 | + for (int i = 6; i < bytes.length; i += macBytes.length) { |
| 29 | + System.arraycopy(macBytes, 0, bytes, i, macBytes.length); |
| 30 | + } |
| 31 | + |
| 32 | + final InetAddress address = InetAddress.getByName(this.wakeStrategy.processIp(ipStr)); |
| 33 | + final DatagramPacket packet7 = new DatagramPacket(bytes, bytes.length, address, 7); |
| 34 | + final DatagramPacket packet9 = new DatagramPacket(bytes, bytes.length, address, 9); |
| 35 | + try (DatagramSocket socket = new DatagramSocket()) { |
| 36 | + socket.setBroadcast(this.wakeStrategy.isBroadcast()); |
| 37 | + // Send to two main WoL ports |
| 38 | + socket.send(packet7); |
| 39 | + socket.send(packet9); |
| 40 | + } |
| 41 | + |
| 42 | + log.info("Wake-on-LAN packet sent to ip: " + ipStr + " mac: " + macStr); |
| 43 | + } catch (Exception e) { |
| 44 | + log.error("Failed to send Wake-on-LAN packet to ip: " + ipStr + " mac: " + macStr + " -> ", e); |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + private static byte[] getMacBytes(String macStr) throws IllegalArgumentException { |
| 49 | + final byte[] bytes = new byte[6]; |
| 50 | + final String[] hex = macStr.split("(\\:|\\-)"); |
| 51 | + if (hex.length != 6) { |
| 52 | + throw new IllegalArgumentException("Invalid MAC address."); |
| 53 | + } |
| 54 | + try { |
| 55 | + for (int i = 0; i < 6; i++) { |
| 56 | + bytes[i] = (byte) Integer.parseInt(hex[i], 16); |
| 57 | + } |
| 58 | + } catch (NumberFormatException e) { |
| 59 | + throw new IllegalArgumentException("Invalid hex digit in MAC address."); |
| 60 | + } |
| 61 | + return bytes; |
| 62 | + } |
| 63 | +} |
0 commit comments