TDD: 1, Me: 0
This commit is contained in:
51
app/wol_utils.py
Normal file
51
app/wol_utils.py
Normal file
@@ -0,0 +1,51 @@
|
||||
import socket
|
||||
import struct
|
||||
# import logging
|
||||
|
||||
# Setup logging
|
||||
# logging.basicConfig(level=logging.DEBUG)
|
||||
|
||||
def create_magic_packet(mac_address):
|
||||
"""Create a magic packet for the given MAC address."""
|
||||
|
||||
# Remove any separation characters from the MAC address
|
||||
mac_address = mac_address.replace(":", "").replace("-", "")
|
||||
|
||||
# Verify length of MAC address
|
||||
# if len(mac_address) != 12:
|
||||
# raise ValueError("Invalid MAC address format")
|
||||
|
||||
# Create the magic packet by repeating the MAC address 16 times
|
||||
mac_bytes = bytes.fromhex(mac_address)
|
||||
magic_packet = b'\xff' * 6 + mac_bytes * 16
|
||||
|
||||
return magic_packet
|
||||
|
||||
def send_magic_packet(mac_address, iface="eth0"):
|
||||
try:
|
||||
|
||||
magic_packet = create_magic_packet(mac_address)
|
||||
|
||||
# Create a raw socket
|
||||
sock = socket.socket(socket.AF_PACKET, socket.SOCK_RAW)
|
||||
# logging.debug(f"Binding to interface: {iface}")
|
||||
sock.bind((iface, 0))
|
||||
|
||||
# Log the packet for debugging
|
||||
# logging.debug(f"Sending Magic Packet: {magic_packet.hex()} on interface {iface}")
|
||||
|
||||
# Construct the Ethernet frame (magic packet)
|
||||
dest_mac = b'\xff\xff\xff\xff\xff\xff' # Broadcast MAC address
|
||||
src_mac = sock.getsockname()[4] # Source MAC address of the interface
|
||||
ether_type = struct.pack('!H', 0x0842) # Wake-on-LAN
|
||||
frame = dest_mac + src_mac + ether_type + magic_packet
|
||||
|
||||
# Send the Ethernet frame
|
||||
sock.send(frame)
|
||||
sock.close()
|
||||
# logging.debug(f"Magic packet sent to {mac_address} on interface {iface}")
|
||||
except Exception as e:
|
||||
logging.error(f"Failed to send WoL packet: {e}")
|
||||
|
||||
# Example usage
|
||||
# send_magic_packet("mac goes here")
|
||||
Reference in New Issue
Block a user